基本兼容性
- 可多不可少
正确示例:
interface TestInterface {
name: string;
}
let p1 = {name: 'BNTang'};
let p2 = {age: 18};
let p3 = {name: 'BNTang', age: 18};
let t: TestInterface;
t = p1;
t = p3;
错误示例:
interface TestInterface {
name: string;
}
let p1 = {name: 'BNTang'};
let p2 = {age: 18};
let p3 = {name: 'BNTang', age: 18};
let t: TestInterface;
t = p1;
t = p2;
t = p3;
- 会递归检查
改造如上接口约束代码,添加子属性如下:
interface TestInterface {
name: string;
children: {
age: number
};
}
然后再次进行测试,正确示例:
interface TestInterface {
name: string;
children: {
age: number
};
}
let p1 = {name: 'BNTang', children: {age: 18}};
let p2 = {name: 'BNTang', children: {age: 'abc'}};
let t: TestInterface;
t = p1;
错误示例,因为 p2
当中的 age 属性是字符串类型:
interface TestInterface {
name: string;
children: {
age: number
};
}
let p1 = {name: 'BNTang', children: {age: 18}};
let p2 = {name: 'BNTang', children: {age: 'abc'}};
let t: TestInterface;
t = p1;
t = p2;