Typescript’s structural subtypes are designed based on how Javascript code is typically written. Because Javascript makes extensive use of anonymous objects, such as function expressions and object literals, it is better to use the structural type system to describe these types than the nominal type system

The basic principle behind Typescript structured types is that if x is compatible with Y, y must have at least the same properties as x:

interface Named{
    name:string;
}
let x:Named;
let y = {name:"paodan",age:12}// y's inferred type is {name:string,age:number}
x = y
console.log(x)//{name:"paodan",age:12}
Copy the code

Here we check to see if y can be assigned to x, and the compiler checks each attribute in X to see if the corresponding attribute can be found in Y. In the above example,y must contain a string member whose name is name. Y satisfies this condition, therefore, the assignment is correct.

interface Named{
    name:string;
}

function greet(n:Named){
    console.log('Hello,'+n.name)//Hello,paodan
}
let y = {
    name:'paodan',
    age:13
}
greet(y)
Copy the code

The code above prints correctly: Hello,paodan Although y has an extra age attribute, this does not raise an error. Only members of the target type (in this case Named) are checked for compatibility. The comparison is performed recursively, checking each member and its children.