首页 > 解决方案 > 类属性作为函数的类型

问题描述

我想将类属性分配为一种函数。但是,函数签名可以有很大的不同。

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,它的值应该是函数类型?该属性很可能是一个胖箭头函数,所以我认为接口不会起作用,但也许通用会起作用?

标签: typescriptfunctiontype-hinting

解决方案


泛型在这里无济于事。您可以简单地键入它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));
    }
}

游乐场链接


推荐阅读