简体   繁体   English

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

[英]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或必须返回stringFunction 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 "";
    }
}

Update 1更新 1

type PropertyFunction<T> = () => T;

interface IExample {
   field : string | PropertyFunction<string>;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在打字稿中定义返回字符串或对象的函数? - How to define a function in typescript that returns string or an object? 返回属性名称字符串文字值的 TypeScript 函数? - TypeScript function that returns value for string literal of property name? Vue3 / Typescript 定义 Array(string) 的属性 - Vue3 / Typescript define an property of Array(string) Typescript:按字符串定义类型 - Typescript: Define type by string 返回 Promise 或 String 的异步函数 - Typescript - Async function that returns a Promise or String - Typescript 是否可以在Typescript中使用预定义的字符串文字类型定义类属性 - Is it possible to define a class property with predefined string literal types in Typescript TypeScript:function 返回一个扩展 Record 的泛型类型<string, string></string,> - TypeScript: function that returns a generic Type which extends Record<string, string> 如何定义在TypeScript 2.0中检查参数是否为字符串的函数 - How to define a function that checks if the parameter is string in TypeScript 2.0 我可以将 Typescript function 参数定义为具有 boolean 类型或字符串吗? - Can I define a Typescript function parameter to have a type of boolean or string? 如何根据Typescript中的字符串参数定义函数的参数类型? - How to define a function's argument type dependent on string argument in Typescript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM