Fernando lugo
Fernando lugo

Reputation: 579

Can I define an interface based on a type?

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

Answers (1)

Jean-Alphonse
Jean-Alphonse

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

Related Questions