简体   繁体   English

如何在打字稿中定义返回字符串或对象的函数?

[英]How to define a function in typescript that returns string or an object?

I have a function that returns string, or an object.我有一个返回字符串或对象的函数。

For example:例如:

myFunc(path: string): string | object

If I know the specific shape of the object I am expecting, how can I use this function so it matches MyObjectProps type instead of object ?如果我知道我期望的对象的具体形状,我如何使用这个函数来匹配MyObjectProps类型而不是object

ie. IE。

type MyObjectProps = {
  a: string;
  b: string;
}

This is easy!这很简单! Just get rid of the 'object' and replace with 'MyObjectProps'只需摆脱“对象”并替换为“MyObjectProps”

myFunc(path: string): string | MyObjectProps

Note that it's considered good practice to use an interface instead of a type where possible:请注意,在可能的情况下使用接口而不是类型被认为是一种很好的做法:

interface MyObjectProps {
  a: string;
  b: string;
}

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

相关问题 将属性定义为在 Typescript 中返回字符串的字符串或函数 - Define a property as string or function that returns a string in Typescript Typescript - 如何使用泛型定义返回对象的可索引属性的函数? - Typescript - How to use generics to define a function that returns indexable properties of an object? 如何定义一个 function 返回一个 object 与基于字符串参数的 getter 和 setter - How to define a function that returns an object with getter and setter based on string argument 如何在Typescript中为function定义readonly object参数 - How to define readonly object parameter for function in Typescript 将函数参数定义为 Typescript 中的对象 - Define function arguments as object in Typescript 如何为函数定义 Typescript 对象返回值? - How can I define a Typescript object return value for a function? 打字稿:如何定义使用泛型引用对象的函数 - Typescript: How to define a function that references an object using generics 如何定义在TypeScript 2.0中检查参数是否为字符串的函数 - How to define a function that checks if the parameter is string in TypeScript 2.0 如何在Typescript中定义拒绝来自对象的键的通用函数? - How to define generic function rejecting key from object in Typescript? 如何在打字稿中为函数定义对象接受的参数类型 - How to define object accepted argument type for function in typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM