typescript - 在 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中做到这一点以确保类型安全?
解决方案
您可以使用索引访问类型和参数实用程序类型(操场)来做到这一点:
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
推荐阅读
- woocommerce - WooCommerce 产品库编辑图片
- flutter - 重新加载小部件树时未重新创建颤振 BlocProvider
- python - 为什么我的函数在通过 if 语句时不起作用?
- java - while((message = reader.readLine()) != null) 是无限循环吗?
- javascript - 如何将文本文件读入 JavaScript 中的对象数组
- javascript - Quill 富文本编辑器:如何将文件输入按钮附加到工具栏并嵌入到编辑器
- javascript - 如何设置状态
- linux - Logstash 在 Ubuntu 中没有显示任何输出
- google-apps-script - 谷歌脚本 DriveApp.getFolders().hasNext() 错误
- javascript - 同时更改范围滑块和输入框的值