In Typescript How Can I Declare Class Method Synonym?
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 {...
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?
2 Answers
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
Why don't you just:
desc( new_desc : string ) : Thing {
return this.description(new_desc);
}