Karedia Noorsil
Karedia Noorsil

Reputation: 470

TypeScript infer type from object keys dynamically

How to create an interface to type check an object based on the keys entered in another object.

For example:

const myObject = {
  colors: {
    black: '#000',
    white: '#fff'
  },
  palette: {
    primary: 'black',
    secondary: 'orange' // <- should give an error because orange does not exist in colors object
  }
};

Upvotes: 2

Views: 2263

Answers (1)

brietsparks
brietsparks

Reputation: 5016

Here is one way

const colors = {
  black: '#000',
  white: '#fff'
};

const palette: Record<string, keyof typeof colors> = {
  primary: 'black',
  secondary: 'white'
};

const myObject = {
  colors,
  palette
};

Upvotes: 1

Related Questions