Why this code do not fail when execute a = b
? Play link
type A = {
x?: number
y?: number
}
type B = {
x?: number
z: number
}
let a: A = {}
let b: B = {z: 1}
a = b // not fail
a = {z: 1} // fail
Why this code do not fail when execute a = b
? Play link
type A = {
x?: number
y?: number
}
type B = {
x?: number
z: number
}
let a: A = {}
let b: B = {z: 1}
a = b // not fail
a = {z: 1} // fail
Typescript uses structural typing (Wikipedia), an object of type B
is a valid A
object.
In your second example, excess property checks will prevent you to assign a literal that has nothing in common with A
.