TypeScript-类型兼容性

2023-09-28 19:29:17 浏览数 (1)

基本兼容性

可多不可少

正确示例:

代码语言:typescript复制
interface TestInterface {
    name: string;
}

let p1 = {name: 'yangbuyiya'};
let p2 = {age: 18};
let p3 = {name: 'yangbuyiya', age: 18};

let t: TestInterface;
t = p1;
t = p3;

错误示例:

image-20211201103028189image-20211201103028189
代码语言:typescript复制
interface TestInterface {
    name: string;
}

let p1 = {name: 'yangbuyiya'};
let p2 = {age: 18};
let p3 = {name: 'yangbuyiya', age: 18};

let t: TestInterface;
t = p1;
t = p2;
t = p3;

会递归检查

改造如上接口约束代码,添加子属性如下:

代码语言:typescript复制
interface TestInterface {
    name: string;
    children: {
        age: number
    };
}

然后再次进行测试,正确示例:

代码语言:typescript复制
interface TestInterface {
    name: string;
    children: {
        age: number
    };
}

let p1 = {name: 'yangbuyiya', children: {age: 18}};
let p2 = {name: 'yangbuyiya', children: {age: 'abc'}};

let t: TestInterface;
t = p1;

错误示例,因为 p2 当中的 age 属性是字符串类型:

代码语言:typescript复制
interface TestInterface {
    name: string;
    children: {
        age: number
    };
}

let p1 = {name: 'yangbuyiya', children: {age: 18}};
let p2 = {name: 'yangbuyiya', children: {age: 'abc'}};

let t: TestInterface;
t = p1;
t = p2;
输入图片说明输入图片说明

最后

本期结束咱们下次再见

0 人点赞