typescript - 使用鉴别器字段创建联合类型的值
问题描述
我的问题最好用一个例子来说明:
interface A { tpe: 'a' }
interface B { tpe: 'b' }
type AB = A | B
const abMaker = (ab: AB): AB => {
return { tpe: ab.tpe }
}
这里的return语句有如下错误:
Type '{ tpe: "a" | "b"; }' is not assignable to type 'B'.
Types of property 'tpe' are incompatible.
Type '"a" | "b"' is not assignable to type '"b"'.
Type '"a"' is not assignable to type '"b"'.
编译器无法推断返回的值是有效AB
的,因为 type 的值对任何一个或单个"a" | "b"
都无效。 A
B
我可以通过“类型检查”的值来使其工作tpe
:
const abMaker = (ab: AB): AB => {
switch (ab.tpe) {
case 'a': return { tpe: ab.tpe }
case 'b': return { tpe: ab.tpe }
}
}
有一个更好的方法吗?
解决方案
推荐阅读
- database - 如何修复安装 mongoDB
- nginx - 如何在带有 nginx 的 debian 9 服务器上通过 https 从 phpmyadmin 发送数据?
- c# - Xamarin iOS - 使用 XCode 编辑的 .xib 的 .cs 和 .designer.cs 文件
- wordpress - 自动将新的 Wordpress 用户添加到 NinjaTables Pro
- flutter - 如何使用 FCM 和 awesome_notifications 只显示一个通知
- python - Python:MemoryError(脚本有时会运行)
- angular - 如何访问 ag-grid 上的标题组件,例如 Cell Editors 组件
- java - Android Navigation View Item 只点击一次
- ios - 并非所有订阅主题的 iOS 设备都会收到数据通知,通常根本没有。没有数据的通知按预期工作
- angular - Angular - 在搜索栏输入上停止可观察的计时器