typescript - 打字稿中的通用类型级别方案
问题描述
我想为函数创建一个输入和输出类型的标记方案,以便将标记传递给函数,它将推断输入和输出类型。
这是一个例子:
type Aa = {
tag: 'a',
a: 2
}
type Ab = {
tag: 'b',
a: 3
}
type TInputMap = {
'a': Aa,
'b': Ab
}
type TResultMap = {
'a': string,
'b': number
}
type A = Ab | Aa;
const fn = <TAction extends keyof TInputMap>(type: TAction, action: TInputMap[TAction]): TResultMap[TAction] => {
if (type === 'a') {
action.a // expected to be 2, but inferred as 2 | 3
}
}
有可能吗?也许使用条件类型?
谢谢。
解决方案
推荐阅读
- asp.net-mvc - 无法将部分视图中的复选框绑定到主模型(MVC)
- linux - VSTS 构建问题文件未找到“git”-Linux 私有代理
- c# - DataTable.Select 将 DateTime 存储为字符串
- python - python中的'import ab as b'和'from a import b'有什么区别
- javascript - JS 代码在函数内部时的行为不同,并被调用
- javafx - 场景中的javafx按钮定位
- jenkins - jenkins build 没有触发 github push
- mysql - MySql - 无法添加外键约束
- typescript - 如何在 ionic 2 中禁用日期时间选择器中的特定日期列表?
- mysql - 多列 SQL 的 Case Then 语句