【问题标题】:Define a property as string or function that returns a string in Typescript将属性定义为字符串或在 Typescript 中返回字符串的函数
【发布时间】:2015-10-29 08:00:46
【问题描述】:

我想创建一个接口,其中属性可以是stringFunction,必须返回string。我目前有以下:

interface IExample {
  prop: string|Function;
}

但这对我来说不够明确,因为Function 可以返回任何东西。我想告诉编译器返回值必须是string

这在 TypeScript 中怎么可能?或者有可能吗?

【问题讨论】:

    标签: typescript declaration tsd


    【解决方案1】:
    type propType = () => string;
    
    interface IExample {
       field : string | propType;
    }
    
    class MyClass1 implements IExample {
        field : string;
    }
    
    class MyClass2 implements IExample {
        field() {
            return "";
        }
    }
    

    更新 1

    type PropertyFunction<T> = () => T;
    
    interface IExample {
       field : string | PropertyFunction<string>;
    }
    

    【讨论】:

    • 像魅力一样工作。旁注:如果有人有更专业的版本,你也可以做类似type StringFunction = () =&gt; string;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 2016-07-17
    • 1970-01-01
    • 2020-09-05
    • 2021-08-10
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多