typescript - Using union type with generic
问题描述
I have a function that accepts a parameter which is an object consisting of a field (string) and arguments (object literal).
I'd like the arguments type check to be validated dependent on what the field is. I also wish to make a definition that can be extended wherever I needed (hence the generic).
Definition:
export interface EventDefinition<
TField extends string,
TArgs extends any
> {
field: TField
arguments: TArgs
}
My function:
export const myFn = (
params:
| EventDefinition<
'actionOne',
{
id: string
}
>
| EventDefinition<
'actionTwo',
{
emailAddress: string
}
>
) => {
const { args, field } = params
switch(field) {
case 'actionOne':
console.log(args.id)
break;
case 'actionTwo':
console.log(args.emailAddress)
break;
}
}
While the field property validates the args do not and result in errors (for ex with args.id):
Property 'id' does not exist on type '{ id: string }'.
Property 'id' does not exist on type '{ emailAddress: string; }'.
How can I correctly define this?
解决方案
Typescript will not guard one variable based on another, this is just not supported.
If you use the argument itself control flow analysis can determine the types appropriately
switch(params.field) {
case 'actionOne':
console.log(params.arguments.id)
break;
case 'actionTwo':
console.log(params.arguments.emailAddress)
break;
}
推荐阅读
- xml - 如何打印此 xml 层次结构中的数据?
- asp.net-mvc - 使用 Entity Framework 和 ASP.NET 时将业务逻辑放在哪里
- ffmpeg - FFMPEG 将 Concat 添加到组合命令
- javascript - 检测用户是否使用 Chrome 扩展 API 切换到 Chrome 以外的其他应用
- c++ - 将字符串映射到类成员
- html - 在输入时:焦点,在不使用 javascript 的情况下也将焦点设置为兄弟元素
- unity3d - unity2d 无法在手机上正确呈现
- c# - 如何允许通过方法调用多个不同的 IList
- couchdb - 在哪里可以找到 CouchDb 设计文档语法的完整参考文档?
- sql - SQL 我如何根据条件对记录进行分组?