Evanss
Evanss

Reputation: 23593

TypeScript define object where keys will be from Type?

How can I define a type for an object where the keys will come from list that I know, in this case field_1 and field_2

type FooKey = 'field_1' | 'field_2';
interface FooValue {
  src: string;
  id: number;
}
interface Foo {
  [FooKey]: FooValue;
}

const thing: Foo = {
  field_1: {
    src: 'src 1',
    id: 1,
  },
  field_2: {
    src: 'src 2',
    id: 2,
  },
};

Upvotes: 0

Views: 25

Answers (1)

Drag13
Drag13

Reputation: 5988

Simply use Record

const d: Record<FooKey, FooValue > = {...}

Upvotes: 1

Related Questions