typescript - 类属性作为函数的类型
问题描述
我想将类属性分配为一种函数。但是,函数签名可以有很大的不同。
export class MyClass {
prop1: string;
prop2: AnotherClass;
prop3: function; // ?
example1() {
this.prop3 = () => 'string';
}
example2() {
this.prop3 = (a, b, c) => new Promise(...);
}
example3() {
this.prop3 = (a) => {
prop: () => 'str'
};
}
}
定义 at 的最短方法是什么prop3
,它的值应该是函数类型?该属性很可能是一个胖箭头函数,所以我认为接口不会起作用,但也许通用会起作用?
解决方案
泛型在这里无济于事。您可以简单地键入它Function
(使用大写字母F
),或者作为您想要允许的签名的并集。
例如,使用Function
(并且| undefined
由于您没有明确为它分配值的构造函数 -| undefined
如果您在真实代码中这样做,请删除):
class MyClass {
prop3: Function | undefined;
example1() {
this.prop3 = () => 'string';
}
example2() {
this.prop3 = (a: string, b: number, c: Date) => new Promise(resolve => resolve(x));
}
}
或者仅使用您分配的两个签名:
class MyClass {
prop3: (() => string) | ((a: string, b: number, c: Date) => Promise<number>) | undefined;
example1() {
this.prop3 = () => 'string';
}
example2() {
this.prop3 = (a: string, b: number, c: Date) => new Promise(resolve => resolve(42));
}
}
推荐阅读
- java - Kotlin 不适用于 vs 代码我已经尝试了所有方法但没有任何效果
- javascript - 当我在反应中要求输入值时,queryselector none
- excel - 使用 Excel 中的 VBA 按钮在表中创建命名为表头的本地命名范围
- kotlin - 选择 Jetpack Compose 中 TextField 的所有文本
- python - 如何在python中将文本分成两部分?
- python - Python:如何用相同的替换字符串替换多个不同的字符串?
- javascript - 链接到 v-for 内的子路由的 router-link 被多次调用(Vue.js 2)
- javascript - 具有和不具有浏览器缩放的相同鼠标位置 (x,y)
- fortran - 为什么 f2py 中的接口定义会引发“语法错误”和“接口块中的意外数据声明语句”错误?
- python - 使用 Spark 读取特定文件(仅限精确匹配)