I have an icon-Map.json which is being created dynamically. Example:
const iconMap = {
angleDoubleRight: 'angleDoubleRight.svg',
angleRight: 'angleRight.svg',
assets: 'assets.svg',
barChart: 'barChart.svg',
cancel: 'cancel.svg',
chevronDown: 'chevronDown.svg',
dotChart: 'dotChart.svg',
dotMenu: 'dotMenu.svg',
horizontalDots: 'horizontalDots.svg'
...
};
I can't create an interface manually from this object because I'm creating it dynamically so I can't use keyof.
Eventually, I want to create a type of iconMap's keys which I can use outside a component and it will strict my input to iconMap's keys only. (union or enum):
type IconMapMember = 'angleDoubleRight' | 'angleRight' | 'assets' | ....
Use an index signature to define a type for an object with dynamic keys, e.g. [key: string]: string; . Index signatures are used when we don't know all of the names of a type's properties ahead of time, but know the shape of the values.
Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings. index.ts.
To dynamically access an object's property: Use keyof typeof obj as the type of the dynamic key, e.g. type ObjectKey = keyof typeof obj; . Use bracket notation to access the object's property, e.g. obj[myVar] .
Dynamic keys are one-time symmetric cryptographic keys. forming a sequence of keys. Similar in nature to one- time pad, every message in the system is encrypted by a. different cryptographic key.
In your question you say you can't use keyof
, but I'm not sure why. If you have an object whose keys are known at compile time (meaning that the iconMap
variable is generated before you compile TypeScript code that uses it), you can use the typeof
type query operator to get its type, and then use keyof
on that:
const iconMap = {
angleDoubleRight: "angleDoubleRight.svg",
angleRight: "angleRight.svg",
assets: "assets.svg",
barChart: "barChart.svg",
cancel: "cancel.svg",
chevronDown: "chevronDown.svg",
dotChart: "dotChart.svg",
dotMenu: "dotMenu.svg",
horizontalDots: "horizontalDots.svg"
//...
};
type IconMapMember = keyof typeof iconMap;
// type IconMapMember = "angleDoubleRight" | "angleRight" | "assets" | "barChart"
// | "cancel" | "chevronDown" | "dotChart" | "dotMenu" | "horizontalDots" ...
Link to code
If you have some particular issue which prevents this solution from working, please update your question with more details about your build process. Hope this helps; good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With