I have the following object in vanilla JS:
const obj = {
foo(val) {
console.log('foo:', val);
return this;
}
bar(val) {
console.log('bar:', val);
return this;
}
}
And I want to decalre this object in my .d.ts
file but I'm not sure what is the best way to define a type for recursive method chaining..
Can someone help with this implementation?
You can define this
in a TypeScript interface:
interface Obj {
[key: string]: (val: string) => this
}
const obj: Obj = {
foo(val) {
console.log('foo:', val);
return this;
},
bar(val) {
console.log('bar:', val);
return this;
}
}
I've assumed that the val
arguments are string.
Edit: I've just seen your comment on your post - you can capture the key dynamically with [key: string]
. I've updated my answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.