Home > Blockchain >  Some Record types are surprisingly considered compatible
Some Record types are surprisingly considered compatible

Time:06-22

I stumbled upon this fairly simple use case in typescript:

type A = { 'a': number }
type B = { [x in number]: A };

let a: A = { a: 42 };
let b: B = a;

Type A and B seems totally unrelated, and I would expect it to fail on the last line but it doesn't. Could someone explain me why ?

CodePudding user response:

This seems to be yet another case of TypeScript's missing excess property checks. Typing the variable b with the type B does not guarantee you that b will only have number-properties. It only guarantees that every number-property will have the type A. The type A actually conforms to this constraint. That's why we can assign a variable of type A to another one of type B.

let b1: B = {} as { a: 123, b: "abc", 0: { 'a': 1 } } // totally fine
let b2: B = {} as { a: 123, b: "abc", 0: "123" } // Error: we broke the type constraint

The only exception is initializing variables or calling functions with object literals like here:

let b3: B = { a: 123, b: "abc", 0: { a: 123} } // Error since object literals are checked for excess properties.

Playground

  • Related