[英]Define a property as string or function that returns a string in Typescript
I want to create an interface where a property can be either a string
or a Function
that has to return a string
.我想创建一个接口,其中属性可以是string
或必须返回string
的Function
。 I currently have the following:我目前有以下几点:
interface IExample {
prop: string|Function;
}
But that's not explicit enough for me because the Function
is allowed to return anything.但这对我来说还不够明确,因为Function
被允许返回任何东西。 I want to tell the compiler that the return value has to be a string
.我想告诉编译器返回值必须是string
。
How is this possible in TypeScript?这在 TypeScript 中怎么可能? Or is it possible at all?或者有可能吗?
type propType = () => string;
interface IExample {
field : string | propType;
}
class MyClass1 implements IExample {
field : string;
}
class MyClass2 implements IExample {
field() {
return "";
}
}
type PropertyFunction<T> = () => T;
interface IExample {
field : string | PropertyFunction<string>;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.