简体   繁体   English

将类型分配给 Typescript 中的通用映射 function 的参数

[英]Assign types to argument of generic mapping function in Typescript

I have a function which maps over an array.我有一个 function 映射到一个数组上。 It looks like this:它看起来像这样:

// opt is either `statusA` | `statusB`
options.map((opt: keyof StatusType) => {
        const activeStatus = statusCollection[opt]; //typescript doesnt scream `of any type` error
        ...

where, StatusType looks like:其中,StatusType 如下所示:

type Keyys = 'statusA' | 'statusB';

export type StatusType = {
  [key in Keyys]: boolean;
};

I did this because i want to be able to retrieve computed property from an object, to store in 'activeStatus' variable above.我这样做是因为我希望能够从 object 中检索计算属性,以存储在上面的“activeStatus”变量中。

This would work fine if the options is always of the type statusType , however, it being an generic function, I want to be able to pass in other collections.如果选项始终是statusType类型,这将正常工作,但是,它是通用 function,我希望能够传入其他 collections。 How would I define the type to replace the 'StatusType' to be more generic & to avail the keyof feature correctly.我将如何定义type以替换“StatusType”以更通用并正确利用keyof功能。

I was on the right track.我走在正确的轨道上。 All I did was create a type for containing the different type definitions using OR |我所做的只是使用 OR |创建一个包含不同类型定义的类型。 . . And passing that as keyof of string type.并将其作为字符串类型的keyof传递。

type TypeContainer = StatusTypeA | StatusTypeB;

options.map((opt: keyof sype) => {
        const activeStatus = statusCollection[opt as keyof TypeContainer];

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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