[英]Typescript get param a by param b in an union type
我有两个请求类型AddInterestAreaRequest
和RemoveInterestAreaRequest
。 我想创建一个 util 类型,我可以在action
中传递它并返回params
。
这就是我所拥有的
type AddInterestAreaRequest = {
action: 'addInterestArea';
params: AddInterestAreaParams;
};
type RemoveInterestAreaRequest = {
action: 'removeInterestArea';
params: RemoveInterestAreaParams;
};
export type JSBRequest = {
configs?: BridgeRequestConfigs;
} & (AddInterestAreaRequest | RemoveInterestAreaRequest);
type GetParamByAction<T extends JSBRequest['action']> =
JSBRequest['action'] extends T ? never : JSBRequest['params'];
type Testing = GetParamByAction<'addInterestArea'>;
我没有工作, Testing
是AddInterestAreaParams | RemoveInterestAreaParams
AddInterestAreaParams | RemoveInterestAreaParams
因为JSBRequest['params']
总是AddInterestAreaParams | RemoveInterestAreaParams
AddInterestAreaParams | RemoveInterestAreaParams
我基本上想Testing
只是AddInterestAreaParams
知道如何实现吗?
谢谢。
您可以使用Extract<T, U>
实用程序类型在类型级别区分可区分联合,该实用程序过滤联合类型T
并仅保留可分配给U
的那些成员:
type GetParamByAction<T extends JSBRequest['action']> =
Extract<JSBRequest, { action: T }>["params"]
因此Extract<JSBRequest, {action: T}>
将仅返回那些action
属性可分配给T
的JSBRequest
成员,这应该正是您想要的。 然后我们对其进行索引以获取其params
属性。
让我们确保它有效:
type Testing = GetParamByAction<'addInterestArea'>;
// type Testing = AddInterestAreaParams
看起来不错。
type GetParamByAction<T extends JSBRequest['action']> = T extends 'addInterestArea' ? AddInterestAreaRequest['params'] : RemoveInterestAreaRequest['params']; type Testing = GetParamByAction<'addInterestArea'>; // Should be AddInterestAreaParams
在这种情况下,我建议使用 TS helper Extract 首先从联合中提取类型:
type GetJSBRequestByAction<T extends JSBRequest['action']> = Extract<JSBRequest, { action: T }>;
type Test1 = GetJSBRequestByAction<'addInterestArea'>;
// This gives:
// {
// configs?: BridgeRequestConfigs;
// } & AddInterestAreaRequest
然后你可以访问参数:
type GetParamByAction<T extends JSBRequest['action']> = GetJSBRequestByAction<T>['params'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.