1

I have the following code:

Playground Link

interface A {
    a: string;
}

interface B {
    a: string;
    b: string;
}

let a: A = {
    a: 'test'
}

let b: B = {
    a: 'test',
    b: 'test2'
}

a = {
    a: 'test',
    b: 'test' // here I have an error, "b" doesn't exist in A
}

a = b; // but here...NO ERROR?

a; // and it's still A

I'm confused. Why can I assign "a" to "b" without an error but I can't assign "a" to an object of type B at the same time? I thought that it works because I changed the type of "a" when assigning it to the variable "b" of type "B" but "a" is still of type "A", yet it contains property "b" now...

What's the explanation for this? Is it somehow related to references?

kzg
  • 780
  • 9
  • 22
  • 1
    https://stackoverflow.com/questions/31816061/why-am-i-getting-an-error-object-literal-may-only-specify-known-properties, so simply put, for object literal assignment, TS thinks the extra field `b` might be unwanted such as typos, but when you assign to object with type B, it knows it is safe to do so. – ABOS Dec 29 '20 at 12:50

0 Answers0