首页 > 解决方案 > type = interface1 或 interface2 ,无法使其工作

问题描述

对不起,如果这个问题已经被问过,但我只看到“接口和类型之间有什么区别”。

所以我的问题是我创建了一种类型,它可以是一个对象/接口或另一个。一个函数接收到这个类型的参数,它会产生一个类型问题。这不容易解释,所以代码会更好: 去 Typescript Playground

我不明白为什么在这种情况下我的变量无法访问,我什至尝试使用类型保护但我无法使其工作。

type Params = {
    a: string;
} | {
    b: string;
    c: number;
}

function test(params: Params) {
    if (params.a !== undefined) {
        console.log("I want to use a there", params.a)
    } else {
        console.log("otherwise it mean b and c are available", params.b, params.c)
    }
}

test({ a: "ok" })
test({ b : "ok", c : 1337 })

提前感谢;)

标签: typescript

解决方案


您需要使用类型保护来缩小类型。那是因为从您的 union typeParams来看,它params.a实际上可能不存在,甚至无法访问。你会发现尝试访问params.bparams.c会给你完全相同的错误。

类型保护应该是'a' in params,以便 TypeScript 可以params自动缩小类型并推断,如果满足此条件,则params必须是 type { a: string },否则,它必须是 type { b: string; c: number; }

function test(params: Params) {
    if ('a' in params) {
        console.log("I want to use a there", params.a)
    } else {
        console.log("otherwise it mean b and c are available", params.b, params.c)
    }
}

请参阅 TypeScript Playground 上的概念验证示例


TypeScript 支持 3 种不同类型的类型保护:


推荐阅读