I have a function which maps over an array. 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:
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.
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. How would I define the type
to replace the 'StatusType' to be more generic & to avail the keyof
feature correctly.
I was on the right track. All I did was create a type for containing the different type definitions using OR |
. And passing that as keyof
of string type.
type TypeContainer = StatusTypeA | StatusTypeB;
options.map((opt: keyof sype) => {
const activeStatus = statusCollection[opt as keyof TypeContainer];
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.