I have an interface called MyInterface
that looks like this:
interface MyInterface<T, K extends keyof T> {
key: K
data: Array<T>
}
I want to constrain the key
prop to be only keys that are present in T and also where the keys in T are only strings. The above interface constrains the key, but not its value to only strings. How can I add this constraint? Some examples of the behavior I'm looking for:
interface Data {
foo: string
bar: number
}
const d: Data[] = [{ foo: 'xxx', bar: 1 }]
// this is valid as the key is in the Data interface and the value of the key is a string
const a: MyInterface<Data, 'foo'> = { key: 'foo', data: d }
// this should be a type error as the value of bar is a number, not a string
const b: MyInterface<Data, 'bar'> = { key: 'bar', data: d }
// this should also be a type error as the key is not in the object
const c: MyInterface<Data, 'baz'> = { key: 'baz', data: d }