dps
dps

Reputation: 864

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

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?

Upvotes: 34

Views: 15269

Answers (1)

dps
dps

Reputation: 864

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

Upvotes: 9

Related Questions