gpt4 book ai didi

javascript - Typescript 接口(interface)作为一系列 OR 接口(interface)

转载 作者:行者123 更新时间:2023-12-02 22:15:03 26 4
gpt4 key购买 nike

有一个接口(interface)可以是多个接口(interface)之一

interface a {x:string}
interface b {y:string}
interface c {z:string}
type all = a | b | c

后来一个对象满足all,因为它的类型是c

调用

    if (obj.hasOwnProperty('z')) {
return obj.z
}

无法编译,因为:

类型“a”上不存在属性“z”。

如何解决这个问题?

最佳答案

如果在您的情况下,可以将 hasOwnProperty 替换为 in 并且您不想定义自定义类型保护 - in will do the job :

interface a { x: string }
interface b { y: string }
interface c { z: string }
type all = a | b | c;

function foo(obj: all) {
if ('z' in obj) {
return obj.z; // obj type is narrowed to c
}
return undefined;
}

Playground

关于javascript - Typescript 接口(interface)作为一系列 OR 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59417788/

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