首页 > 解决方案 > 在 TypeScript 中如何声明类方法的同义词?

问题描述

我想定义应该与其他类方法相同并返回相同值的类方法。像这样的东西:

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( ? ) {
        ?
    }
}

在纯JavaScript 中,我会这样做:

class Thing {
    _description
    description( new_desc ) {
        this._description = new_desc
        return this
    }

    desc() {
        return this.description.apply( this, arguments )
    }
}

但它显然打破了所有类型的推断和安全性。

如何在TypeScript中做到这一点以确保类型安全?

标签: typescript

解决方案


您可以使用索引访问类型参数实用程序类型(操场)来做到这一点:

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

推荐阅读