Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In TypeScript how can I declare class method synonym?

Tags:

typescript

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?

like image 546
Slaus Avatar asked Jan 24 '26 04:01

Slaus


1 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
like image 107
Mirco S. Avatar answered Jan 25 '26 22:01

Mirco S.