将属性定义为在Typescript中返回字符串的字符串或函数

问题描述 投票:5回答:1

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

interface IExample {
  prop: string|Function;
}

但是对我来说这还不够明确,因为允许Function返回任何内容。我想告诉编译器,返回值必须为string

在TypeScript中怎么可能?还是有可能?

typescript declaration tsd
1个回答
11
投票
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>;
}
© www.soinside.com 2019 - 2024. All rights reserved.