![](/img/trans.png)
[英]Define a property as string or function that returns a string in Typescript
[英]How to define a function in typescript that returns string or an object?
我有一個返回字符串或對象的函數。
例如:
myFunc(path: string): string | object
如果我知道我期望的對象的具體形狀,我如何使用這個函數來匹配MyObjectProps
類型而不是object
?
IE。
type MyObjectProps = {
a: string;
b: string;
}
這很簡單! 只需擺脫“對象”並替換為“MyObjectProps”
myFunc(path: string): string | MyObjectProps
請注意,在可能的情況下使用接口而不是類型被認為是一種很好的做法:
interface MyObjectProps {
a: string;
b: string;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.