Instead of using keyof T
, you presumably want a stricter type which only allows keys with string | number
values. Here's a solution:
type KeysAssignableTo<T, V> = {[K in keyof T]: T[K] extends V ? K : never}[keyof T]
interface IProps<T> {
item: T;
key: KeysAssignableTo<T, string | number>;
}
Examples:
const item = {foo: 1, bar: true}
// OK
const testOK: IProps<typeof item> = {item, key: 'foo'}
// error: Type 'bar' is not assignable to type 'foo'
const testBad: IProps<typeof item> = {item, key: 'bar'}
Playground Link