Keyof for Nested Objects
·
1 min read
Problem
interface User {
parent: {
name: string;
};
age: number;
name: string;
}
type Column = {
key: keyof User;
};
const columns: Column[] = [
{
key: 'name'
},
{
key: 'name1'
},
{
key:'parent.name'
}
];
Solution
type Paths<T> = T extends object ? { [K in keyof T]:
`${Exclude<K, symbol>}${"" | `.${Paths<T[K]>}`}`
}[keyof T] : never
type Column = {
key: Paths<User>;
};
In addition to writing your own Paths
type, you can also use existing libraries, such as the Path
type from type-fest
.
Result
const columns: Column[] = [
{
key: 'name'
},
{
key: 'parent.name' // ok
},
{
key: 'parent.name1' // error
}
];