2

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
  }
};
1
  • 1
    There is no specific interface in TypeScript which works this way. You could take this approach and represent your object type as a generic constraint, using an asMyObject() helper function to infer the generic type. Does that meet your needs? If so I can write up an answer; if not, please let me know what I'm missing about your use cases. Commented Jan 9, 2022 at 1:57

1 Answer 1

1

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
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.