Ruslan Plastun
Ruslan Plastun

Reputation: 2254

Record type is not compatible with specific object type

Why this piece of code does not work? beta indeed has keys of type string and their values are compatible (id is indeed number type, and temp is indeed number type), and most of all Record makes values of all keys any, and any should be compatible with everything.

const alpha:  Record<string, any> = {
  id: 1,
  temp: 2
};

const beta : {
  id: number;
  temp: number
} = alpha;

Then why it says that?

Type 'Record<string, any>' is missing the following properties from type '{ id: number; temp: number; }': id, temp

Upvotes: 2

Views: 771

Answers (1)

beta expects id and temp properties.

Because you have provided explicit type for alpha, TS treats alpha as Record<string, any> and not as {id: number; temp: number}.

Hence, there is no guarantee that Record<string, any> contains id and temp.

You need to remove explicit type from alpha.

Try to avoid explicit types in such cases, TS most of the time should do the work for you.

const alpha = {
  id: 1,
  temp: 2
};

const beta : {
  id: number;
  temp: number
} = alpha;

This is how TS treats these variables:

declare let alpha: Record<string, any>;

declare let beta: { id: number; temp: number };

alpha = beta // ok

beta = alpha // error

As you might have noticed, beta is assignable to alpha, so you can provide explicit type Record<string, any> for alpha object.

But it does not work in opposite direction - alpha is not assignable to beta because beta is a subtype of alpha

Treat alpha as a super type and beta as a subtype

Upvotes: 2

Related Questions