typescript - TypeScript 处理类型数组或单个值
问题描述
我有一个这样的界面。我想知道处理这种情况的最佳情况是什么:
interface Ia {
a: string
}
let a: Ia | Ia[]
console.log(a[0].a)
TS 给我一个错误:
Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'Ia'.
Property '0' does not exist on type 'Ia'.
我知道我可以使用console.log((a as Ia[])[0].a)
,但它根本不可读。有没有人有更好的建议?
此外,真正的用例类型内部有许多属性,而不是a: sting
示例中的单个属性。
解决方案
如果a
不是数组,则a[0]
没有意义。您需要测试它是否是一个数组,并根据该测试的结果对其进行不同的处理。
interface Ia {
a: string
}
let obj: Ia | Ia[] = { a: 'foo' };
function test(obj: Ia | Ia[]): void {
console.log(Array.isArray(obj) ? obj[0].a : obj.a);
}
或者您可以使用这种利用控制流类型缩小的模式:
function test2(obj: Ia | Ia[]): void {
if (Array.isArray(obj)) { obj = obj[0]; }
// now obj: Ia is known not to be an array
console.log(obj.a);
}
推荐阅读
- android - 在应用程序上颤振“演示”树桩
- sql - 在下面的代码中,如果最后一个查询没有返回reject_count(因为表中没有拒绝),那么这个查询下面的语句没有执行
- algorithm - O(mn) 比 O((m+n)^2) 好吗?
- spring - Feign 客户端尝试联系实例,即使它们已关闭
- javascript - 如何从 URL.createObjectURL 显示音频 html src
- javascript - ReferenceError: d3 is not defined free code camp
- ethereum - 如何在我的本地 Geth 帐户中获取一些以太币?
- javascript - 如何修复 TypeError:无法读取未定义的属性?
- java - 从 Java 程序到 Python 程序的自定义输入
- spring - 如何在 Spring Boot 中配置数据库连接运行时?