【问题标题】:Class property as type of function类属性作为函数的类型
【发布时间】:2021-02-04 00:59:11
【问题描述】:

我想将类属性指定为一种函数。但是,函数签名可能会有很大差异。

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'
        };
    }
}

prop3 定义它的值应该是函数类型的最短方法是什么?该属性很可能是一个粗箭头函数,所以我认为接口不会起作用,但也许泛型会起作用?

【问题讨论】:

    标签: typescript function type-hinting


    【解决方案1】:

    泛型在这里无济于事。您可以将其输入为简单的Function(大写为F),或者您希望允许的签名的union

    例如,使用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));
        }
    }
    

    Playground link

    或者仅使用您分配的两个签名:

    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));
        }
    }
    

    Playground link

    【讨论】:

    • 当我尝试使用 Function | undefined 我得到 Property '...' does not exist on type 'Function'
    • @myol - 当你得到它时,你想使用什么属性?你在什么代码上得到这个错误?
    • 在这种情况下,箭头函数包含另一个箭头函数的属性
    • @myol - “包含属性”是什么意思?你的意思是你在函数对象上有一个属性? (不寻常,但可能。)还是什么?您的问题中没有代码显示使用this.prop3 上的属性。
    • @myol - 更新中的代码可能不是您的意思。你有this.prop3 = (a) =&gt; { prop: () =&gt; 'str' };,它创建了一个不做任何事情的函数。它没有返回值,其内容是单个标记表达式(不是属性)。调用它没有效果。
    【解决方案2】:

    您可以使用 '() => type' 语法来执行此操作。您也可以以多种不同的方式定义输入,在这种情况下它可能是这样的

    prop3: (a: string, b: number, c: T) => Promise<Y>
    

    也就是说,您只能将具有 3 个参数作为输入并返回 Y 类型的 Promise 的函数分配给 prop3。或者您可以执行类似的操作

    prop3: (...args: number[]) => Promise<T>
    

    这里说 prop3 可以是一个函数,它接受可变数量的数字并返回 T 类型的承诺。如果你有其他类型需要在下面发布它们,Typescripts 类型系统在这方面非常灵活尊重。

    【讨论】:

      猜你喜欢
      • 2020-05-07
      • 2019-03-31
      • 2021-04-09
      • 2012-09-14
      • 2022-11-17
      • 2016-05-13
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多