typescript - 精炼打字稿不相交的联合
问题描述
我正在尝试使以下内容起作用,但是打字稿在尝试访问该o.foo
属性时输出错误:
type Base = { s: string };
type Extra = { foo: string; };
type Other = { bar: string; };
type T = Base & (Extra | Other);
function f(o: T): string {
if (typeof o.foo === 'string') {
return o.s + o.foo;
}
return o.s + o.bar;
}
错误是
Property 'foo' does not exist on type 'T'.
Property 'foo' does not exist on type 'Base & Other'.
似乎打字稿无法正确推断出如果o
有一个foo
属性,即字符串,那么 of 的类型o
必须在Base & Extra
联合的分支中。
有没有办法让它明白这一点?
解决方案
除非他们很常见,否则您无法访问工会成员。您可以改用in
typeguard:
type Base = { s: string };
type Extra = { foo: string; };
type Other = { bar: string; };
type T = Base & (Extra | Other);
function f(o: T): string {
if ('foo' in o) {
return o.s + o.foo;
}
return o.s + o.bar;
}
推荐阅读
- webpack - Nativescript webpack 捆绑全局变量
- encryption - 在 Inno Setup 中对字符串进行编码并将值保存到文件中
- filesystems - 使用 fdisk 更改分区会显示类似“partition#x contains ext4-signature”的警告
- html - RadioField 永远不会正确验证
- algorithm - 在 DAG 中寻找哈密顿路径的算法的正确性证明
- html - Flexbox CSS 中的溢出滚动项右侧没有空间
- javascript - 如何在下拉列表中设置正确的值
- dart - Dart 映射函数作为具有节点互操作的构造函数
- r - R 如何拟合第一个观察点 arima?
- javascript - 如何通过 AJAX 显示来自 MySQL 的 BLOB 图像?