Reputation: 579
How can I define an interface with its keys based on a type? e.g:
type FruitTypes = "bananna" | "appple " | "orange";
interface FruitInterface {
[key: string]: any; // key FruitTypes instead of string
}
// Expected result:
const FruitsObject: FruitInterface = {
bananna: "Bannana",
apple: "Apple",
orange: "Orange",
mango: "Mango" // Error
};
I've tried something like this:
interface FruitInterface {
[key: keyof FruitTypes]: any;
}
Maybe there is another way of doing it?.
Thanks in advance.
Upvotes: 0
Views: 35
Reputation: 816
This behaves like you want it to:
const FruitsObject: Record<FruitTypes, any>
Is there a specific reason you need an interface ? This is also possible:
interface FruitInterface extends Record<FruitTypes, any> {}
const FruitsObject: FruitInterface
Upvotes: 1