typescript - 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 })
提前感谢;)
解决方案
您需要使用类型保护来缩小类型。那是因为从您的 union typeParams
来看,它params.a
实际上可能不存在,甚至无法访问。你会发现尝试访问params.b
或params.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 种不同类型的类型保护:
推荐阅读
- javafx - 将值从数组更改为组合框
- blockchain - 如何运行 Elrond 节点(验证器)?
- google-api - Google Ads 的“操作”和“请求”有什么区别?
- oracle - oracle数据库中密码不能包含用户名或用户全名的一部分(pl/sq)
- apache-kafka - 如何修复 kafka.common.errors.TimeoutException: Expiring 1 record(s) xxx ms has been given since batch creation plus linger time
- android - 无法在 web 视图中录制语音
- python-3.x - 模板文件夹中的烧瓶 url_for 'static'?
- c++ - 如何修复元素
在 C++ 中有无效值“/Yu”错误? - mongodb - Kafka 连接器未读取 mongodb 集合
- java - 如何修复就餐 simphony 错误:saf.v3d.scene.VComposite.addChild(VComposite.java:46)