[英]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.