Type '{}' is not assignable to type 'Record<Key, Value>'

Viewed 6912

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?

2 Answers

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

Because Record is not a replace type for the object type.

Related