gpt4 book ai didi

Typescript - 键/属性类型保护

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:05 24 4
gpt4 key购买 nike

我可以创建一个类型保护来断言对象中存在特定属性(或具有特定类型)吗?

我有一个接口(interface)Foo:

interface Foo {
bar: string;
baz: number;
buzz?: string;
}

现在 Foo 类型的对象将有一个可选的属性 buzz。我将如何编写断言 buzz 存在的函数:即

const item: Foo = getFooFromSomewhere();

if (!hasBuzz(item)) return;

const str: string = item.buzz;

我将如何实现 hasBuzz()?类似于类型保护的东西:

function hasBuzz(item: Foo): item.buzz is string {
return typeof item.buzz === 'string'
}

有这样的东西吗?

PS:我知道我可以做到:

const item = getFooFromSomewhere();

if (typeof item.buzz === 'string') return;

const str: string = item.buzz;

但我的实际用例要求我有一个单独的函数来断言 buzz 的存在。

最佳答案

我不喜欢这里现有的答案,因为它们都是针对检查 Foo 的对象,但您可以定义一个 hasBuzz typeguard 将检查任何 对象以查看它是否具有 buzz属性(property)。

interface Buzzable {
buzz: string;
}

function hasBuzz<T extends {buzz?: any}>(obj: T): obj is T & Buzzable {
return typeof obj.buzz === "string";
}

通过使用通用 T用于输入和返回 obj is T & Buzzable而不仅仅是 obj is Buzzable您不会丢失有关特定接口(interface)的任何信息,例如 Foo使用 hasBuzz 检查时.

如果hasBuzz(item: Foo)true , 然后 typescript 知道 item 的类型是Foo & Buzzable .在这种情况下,它与 Required<Foo> 相同自 Foo有一个可选的 buzz属性,但您可以检查任何对象。 hasBuzz({})完全有效,应该总是返回 false .

Typescript Playground Link

关于Typescript - 键/属性类型保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58215092/

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