gpt4 book ai didi

typescript - 从窄类型和宽类型数组推断类型

转载 作者:行者123 更新时间:2023-12-04 14:51:03 25 4
gpt4 key购买 nike

type ItemNew = { text: string };
type ItemExist = { text: string, id: number };

function fn(
itemsNew: Array<ItemNew>,
itemsExist: Array<ItemExist>
) {
const items = [...itemsNew, ...itemsExist];
// const items: ItemNew[]
}

为什么 itemsItemNew[]而不是 Array<ItemNew | ItemExist> ?似乎有关宽类型 ( ItemExist) 的信息完全丢失了。

最佳答案

考虑这个例子:

type ItemNew = { text: string };
type ItemExist = { text: string, id: number };

type Union = ItemNew | ItemExist
declare var union: Union

const elem = union.text // only text property is allowed

因为 text对于您被允许获得的两种元素都很常见 text属性(property)。

因为没有人知道var union包含 id或不。允许id prop 在这种情况下将是不健全的(可能导致运行时错误)。

让我们回到你的例子:

type ItemNew = { text: string };
type ItemExist = { text: string, id: number };

function fn(
itemsNew: Array<ItemNew>,
itemsExist: Array<ItemExist>
) {
const items = [...itemsNew, ...itemsExist];
}

事实上itemsArray<ItemNew> | Array<ItemExist> 的并集.应用相同的规则。属性(property)text是唯一一个安全的属性。

如果你想能够得到id Proeprty 你可能不会使用这个助手:

type ItemNew = { text: string };
type ItemExist = { text: string, id: number };

// credit goes to https://stackoverflow.com/questions/65805600/type-union-not-checking-for-excess-properties#answer-65805753
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> =
T extends any
? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;

type StrictUnion<T> = StrictUnionHelper<T, T>


function fn(
itemsNew: Array<ItemNew>,
itemsExist: Array<ItemExist>
) {
const items: Array<StrictUnion<ItemNew | ItemExist>> = [...itemsNew, ...itemsExist];
items[0].text // ok
items[0].id // number | undefined
}

关于typescript - 从窄类型和宽类型数组推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69100845/

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