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 {
    _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);
}
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest