繁体   English   中英

Typescript 在联合类型中通过参数 b 获取参数 a

[英]Typescript get param a by param b in an union type

我有两个请求类型AddInterestAreaRequestRemoveInterestAreaRequest 我想创建一个 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'>;


我没有工作, TestingAddInterestAreaParams | 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属性可分配给TJSBRequest成员,这应该正是您想要的。 然后我们对其进行索引以获取其params属性。

让我们确保它有效:

type Testing = GetParamByAction<'addInterestArea'>;
// type Testing = AddInterestAreaParams

看起来不错。

Playground 代码链接

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM