gpt4 book ai didi

javascript - 无法从联合类型访问参数 (TypeScript)

转载 作者:行者123 更新时间:2023-11-30 09:45:18 25 4
gpt4 key购买 nike

为什么不能像这样访问联合类型中的属性:

export interface ICondition {
field: string
operator: string
value: string
}

export interface IConditionGroup {
conditions: ICondition[]
group_operator: string
}

function foo(item: ICondition | IConditionGroup) {
if(typeof item.conditions === "undefined") { // does not work
let field = item.field; // does not work
///.. do something
} else {
let conditions = item.conditions; // does not work
/// .. do something else
}
}

我收到这些错误:

error TS2339: Property 'conditions' does not exist on type 'ICondition | IConditionGroup'.
error TS2339: Property 'conditions' does not exist on type 'ICondition | IConditionGroup'.
error TS2339: Property 'field' does not exist on type 'ICondition | IConditionGroup'.

但我必须转换类型才能让它工作 - 就像这样:

function foo2(inputItem: ICondition | IConditionGroup) {
if(typeof (<IConditionGroup>inputItem).conditions === "undefined") {
let item= (<ICondition>inputItem);
let field = item.field;
///.. do something
} else {
let item= (<IConditionGroup>inputItem);
let conditions = item.conditions;
/// .. do something else
}
}

我知道类型信息在 JS 中丢失了,那么为什么我必须在 TS 中显式转换它?

最佳答案

Typescript 使用 Type Guards 处理这个问题,通常很简单:

if (typeof item === "string") { ... } else { ... }

或者

if (item instanceof MyClass) { ... } else { ... }

但在您的情况下,因为您使用的是不可能的接口(interface),所以您需要创建自己的 User-Defined Type Guards :

function isConditionGroup(item: ICondition | IConditionGroup): item is IConditionGroup {
return (item as IConditionGroup).conditions !== undefined;
}

function foo(item: ICondition | IConditionGroup) {
if (isConditionGroup(item)) {
let conditions = item.conditions;
// do something
} else {
let field = item.field;
// do something else
}
}

( code in playground )

你也可以在没有类型保护的情况下这样做:

function foo(item: ICondition | IConditionGroup) {
if ((item as IConditionGroup).conditions !== undefined) {
let conditions = (item as IConditionGroup).conditions;
// do something
} else {
let field = (item as ICondition).field;
// do something else
}
}

但这太冗长了,因为您需要键入 assert item 3 次而不是一次。

关于javascript - 无法从联合类型访问参数 (TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39127929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com