Home > Net >  Is it possible to get types from an unknown array?
Is it possible to get types from an unknown array?

Time:07-15

I am getting Icon names from an imported library and mapping through them like this:

import * as Icons from "@icons";

// an array of icon names ["ArrowLeft", "ArrowRight" ect]
const IconNames = [...Object.keys(Icons).map((icon) => icon)] as const; 
// for sizes prop
const IconSizes = ["sm", "md", "lg"] as const; 

But when I try to get types from the array it just comes up as string:

icon: typeof IconNames[number]; //this is type string
size: typeof IconSizes[number]; //this is type "sm" | "md" | "lg"
};

Am I doing something wrong or is it not possible to get the type for icon from an unknown array "ArrowLeft" | "ArrowRight"?

Any help would be great.

Thanks

CodePudding user response:

Yeh this is a gap in TypeScript: https://github.com/microsoft/TypeScript/pull/12253#issuecomment-263132208.

Your only choice is to cast it to keyof Icons.

  • Related