I want to define class method which is supposed to do the same as other class method and return the same value. Something like that:
class Thing {
_description : string
description( new_desc : string ) : Thing {
this._description = new_desc
return this
}
/** And here I want to define method which is doing absolutely the same and
returning the same value, but targeting API users that are lazy to type.*/
desc( ? ) {
?
}
}
In plain JavaScript I would do it like this:
class Thing {
_description
description( new_desc ) {
this._description = new_desc
return this
}
desc() {
return this.description.apply( this, arguments )
}
}
But it obviously breaks all the types inference and safety.
How can I do it in TypeScript to ensure type-safety?
You can do this with index access types and the Parameters utility type (playground):
class Thing {
private _description = "";
description( new_desc: string ) {
this._description = new_desc
return this
}
desc(...args: Parameters<Thing["description"]>) {
return this.description.apply( this, args )
}
}
const test = new Thing();
test.description("test");
test.desc("test");
test.desc(5) // error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With