How do I restrict the keyof
to only accept keyof
where the type is of specified type?
interface Data {
items: string[];
name: string;
}
// so far this accepts any valid key of `T`.
// I want to restrict this so that it only allows keys where the value of the key is type `F`
type Key<T, F = any> = keyof T & string;
interface TextField<T> {
input: 'text'
key: Key<T, string>
}
interface ArrayField<T> {
input: 'text',
key: Key<T, Array>
}
type Field<T> = TextField<T> | ArrayField<T>;
// Should NOT error
const config: Field<Data>[] = [
{
input: 'text'
key: 'name'
},
{
input: 'array',
key: 'items'
}
];
// Should error because the items is not a string and name is not an array
const config: Field<Data>[] = [
{
input: 'text'
key: 'items'
},
{
input: 'array',
key: 'name'
}
]