Reputation: 470
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
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