typescript - object foo 有两个 props bar 和 baz ,如何通过 bar 的值推断 baz 类型
问题描述
type OneType = {a: string};
type TwoType = {b: number};
type DefineItem = {
bar: 'one' | 'two',
baz: OneType | TwoType
};
const items: DefineItem = {
bar: 'one',
baz: ???
}
预计:
当 bar === 'one' 时,推断 baz 的类型是 OneType
当 bar === 'two' 时,推断 baz 的类型是 TwoType
解决方案
您可以定义两种类型的有区别的联合:
type OneType = {a: string};
type TwoType = { b: number };
type DefineItem = {
bar: 'one',
baz: OneType
} | {
bar: 'two',
baz: TwoType
};
const item1: DefineItem = {
bar: 'one',
baz: { a: 'hello' }
}
const item2: DefineItem = {
bar: 'two',
baz: { b: 5 }
}
推荐阅读
- ios - 平移手势(按住/拖动)缩放相机,如 Snapchat
- php - 如何在函数中调用mysqli查询
- wordpress - 我可以通过 Wordpress API 获取 Wordpress 插件数据吗?
- kubernetes - 如何更改在一个端口号上运行的服务,现在我想在同一个旧端口号上运行另一项服务
- html - 如何使用我从 css 文件中导入的字体
- python-3.x - 如何使用starts_with jmespath.search 字典键
- python - 如何评估 Jupyter Notebook 中的分数(代入变量值)?
- javascript - Chrome DevTools:如何从 Sources 选项卡或 Watch 窗格中将 JSON 对象复制为文本
- spring-boot - Spring Boot 安全性在响应标头 cookie 中添加 2 个 XSRF-TOKEN
- php - PHP Laravel PDOException 一般错误引用列和外键约束中的引用列不兼容