I have the following code:
const foo = <Key extends keyof any, Value>() {
type Rec = Record<Key, Value>
const a: Rec = {}
}
On the 3rd line typescript given an error that Type '{}' is not assignable to type 'Record<Key, Value>
. Why is that happening?
In my case generic parameter was string
and it's okay to assign empty object to Record<string, unknown>
.
Reason why it is not accepting {}
is that Key
parameter could be concrete string union type like 'prop1' | 'prop2'
. In this case user is forced to add these properties to the object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With