typescript - 打字稿需要密钥 A 或密钥 B
问题描述
我是打字稿的新手
我有一个接口 ABC,我希望 propA 或 propB 在那里。它还有其他属性
interface ABC {
propA: string
propB: string
propC: string
propD?: string
}
我怎样才能做到这一点?
我是根据这个答案做的https://stackoverflow.com/a/40510700/10433835
interface ABC {
propC: string
propD?: string
}
interface A extends ABC {
propA: string
}
interface B extends ABC {
propB: string
}
export type final = A | B
但是当我做这样的事情时
function somethingCalled (a:A) {
}
const b:final = req.body
somethingCalled(b)
它引发以下错误 Argument of type 'final' is not assignable to parameter of type 'interface A'。
解决方案
我认为您想要的是使用区分联合,其中联合的单个对象由区分它们的属性来区分。在您的情况下,propA
告诉它是A
并且propB
告诉它是B
。以下是我们如何使用它们:
interface ABC {
propC: string
propD?: string
}
interface A extends ABC {
propA: string
anotherA: number;
}
interface B extends ABC {
propB: string
somethingB: boolean;
}
export type FinalType = A | B
function somethingCalled (a:FinalType) {
if('propA' in a){
a.anotherA
a.somethingB; // Error: Property 'somethingB' does not exist on type 'A'
} else {
a.somethingB
a.anotherA // Error: Property 'anotherA' does not exist on type 'B'.
}
}
const req: any = '';
const b:FinalType =( req as any).body
somethingCalled(b)
一旦明确区分,您可以看到 Typescript 如何判断其他属性不属于该类型。
TS Playground 链接:https ://tsplay.dev/mpvDpw
推荐阅读
- typescript - Why does this Firebase Cloud Function function produce the error 'Error: function crashed out of request scope Function invocation was interrupted.'
- c# - VS Winforms: Components (images, buttons, labels) are resizing and stretching on build
- javascript - Javascript:定义为箭头函数的覆盖方法在父级中看不到
- c# - 如何为定制的浏览器构建 javascript 解释器?
- swift - 如何防止用户在 Swift 5 的 UITextView 中添加太多换行符?
- botframework - 如何将参数发送到回发对话框
- javascript - 我可以从 Redux 中的一个 reducer 获得多个状态吗?
- flutter - how to fix align issue on tabbar
- python - 没有 while True: ? 时无法启动输入命令。while True 的重要性和替代项:?
- perl - 用右侧的空格规范化列填充