#Extending a chain api in typescript
7 messages · Page 1 of 1 (latest)
Preview:```ts
const generic = function () {
const api = {
_deleted: false,
delete() {
this._deleted = true
return this
},
}
return api
}
const comment = function () {
const api = {
...generic(),
_text: "",
edit(text: string) {
this._text = text
...```
you need to use a this parameter to specify the type
Is there a reason why you are writing it with objects rather than classes? This seems like a perfect use case.
Preview:```ts
class Entity {
deleted = false
public delete() {
this.deleted = true
return this
}
}
class CommentEntity extends Entity {
text = ""
public edit(text: string) {
this.text = text
return this
}
}
new CommentEntity().delete().edit("hello world")
...```
if you do need to avoid classes for some reason, here's a version that uses a this parameter:
Preview:```ts
const generic = function () {
const api = {
_deleted: false,
delete<T extends {_deleted: boolean}>(this: T) {
this._deleted = true
return this
},
}
return api
}
const comment = function () {
const api = {
...generic(),
...```