我有一个带有函数类型的类型别名。
type ADD_FUNCTION = (x: number, y: number) => number;
我可以做这个:
type ADD_FUNCTION = (x: number, y: number) => number;
const add: ADD_FUNCTION = (x, y) => {
return x + y;
};
const result = add(1,2);
console.log(result);
Run Code Online (Sandbox Code Playgroud)
它之所以有效,是因为我将函数存储到一个名为addtype的变量中ADD_FUNCTION。
但是,如果我不想将该函数存储在变量中并使用常规命名函数声明它怎么办?
function add(x,y) {
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
type是否有一种语法允许我使用别名定义该函数类型ADD_FUNCTION?
以下代码不起作用:
function add: ADD_FUNCTION (x,y) {
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
注意:我知道以下代码是可能的,但我真的很想使用type alias.
function add(x: number, y: number): number {
return …Run Code Online (Sandbox Code Playgroud) 比方说,我有一个方法将其功能委托给外部库中的某个方法,并且我有一个该外部方法的类型,例如LibDoStuffMethodType.
class MyApp {
doStuff(args) {
// delegate to external library's lib.doStuff
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如何指定我的方法的类型MyApp.doStuff()?当然,我可以将doStuff()MyApp 的属性设置为:
class MyApp {
doStuff: LibDoStuffMethodType
}
Run Code Online (Sandbox Code Playgroud)
但这是不可取的,原因有多种(其中之一是 IntelliSense 支持,我们宁愿在 IntelliSense 建议中看到它doStuff()是一个实际方法,而不是属性,方法和属性的颜色和标记不同)。
所以,问题是:有什么方法可以将方法保留为方法,但以某种方式指定其完整类型LibDoStuffMethodType?