I want to create a generic solution for a type safe array of key value pairs
suppose we have a type like this:
type Person = {
name: string,
age: number,
}
I want to define KeyValArr type to have a type safe solution for usage below:
const myPersonKV: KeyValArr<Person> = [
{ key: 'name', value: 'john' },
{ key: 'age', value: 22 }
]
The solution I had on my mind was to define KeyValArr as below:
type KeyValArr<T> = {
key: keyof T,
value: T[keyof T]
}[]
but the problem with this approach is that the code below does not result in any error:
const tmp: KeyValArr<Person> = [
{ key: age, value: 'wrong type!' }
]
how can I define KeyValArr in a way to have type safety on value based on the defined key?
Person[]?[]on theKeyValArrtype and edited it. Is there any other typo?