TypeScript-接口

版权声明:本文为博主原创文章,转载请注明出处 thx~ https://blog.csdn.net/x550392236/article/details/88710023

interface接口:只要传入的对象满足接口的必要条件,那么它就是被允许的。

// 声名一个testType的接口
interface testType {
    name: string;
    age: number;
}

function test(obj: testType) {
    console.log(obj.name);
    console.log(obj.age);
}

test({ name: "xia", age: 20, height: 180 });
// height: 180 将会报错提示,但仍然能编译并打印出   xia 20

.

可选属性(接口定义中加“?”)

interface testType {
    name: string;
    age: number;
    height?: number;
}
function test(obj: testType): void {
    console.log(obj.name);
    console.log(obj.age);
    console.log(obj.height);
}
test({ name: "xia", age: 20, height: 180 });  // xia 20 180
// height 不传也不会报错

.

只读属性(readonly)

interface testType {
    readonly name: string;
    age: number;
}

let test: testType = { name: "张三", age: 20 }

test.name = "李四";
// name是只读属性不能修改,会报错提示,但仍然能编译并修改成功

.

接口继承(extends)

interface nameFace {
    name: string;
}
interface ageFace {
    age: number;
}
interface heightFace extends nameFace, ageFace {
    height: number;
}

let person = <heightFace>{};
person.name = "xia";
person.age = 20;
person.height = 180;

.

接口继承类

class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};

类实现接口 (implements)

interface Animal {
    eat(): any
}

// Sheep类实现Animal接口
class Sheep implements Animal {
    eat() {  // 必须调用eat()方法 否则报错
        // ...
    }
}

class Cat implements Animal {
    eat() {  // 必须调用eat()方法 否则报错
        // ...
    }
}

猜你喜欢

转载自blog.csdn.net/x550392236/article/details/88710023
今日推荐