TypeScript快速入门 - 接口

发布时间:2024年01月12日

TypeScript接口

1、关键字:interface

interface IUser {
    name: string
    age: number
}

let user: IUser = {name: "张三", age: 22};
console.log(user);

// {name: "张三", age: 22}

2、接口的继承

? ? ? ? 关键字:extendes

interface IUser {
    name: string
    age: number
}

let user: IUser = {name: "张三", age: 22};
console.log(user);

// {name: "张三", age: 22}

// 接口可以继承
interface IStudent extends IUser {

}

let student: IStudent = {name: "李四", age: 18};

console.log(student);
// {name: "李四", age: 18}

3、接口的可选参数

? ? ? ? 关键字: ?

interface IUser {
    name: string
    age: number
}

let user: IUser = {name: "张三", age: 22};
console.log(user);

// {name: "张三", age: 22}

// 接口可以继承
// CET6?: 代表CET6是可选参数,可有可无,而CET4参数则必须得有
interface IStudent extends IUser {
    CET4: boolean
    CET6?: boolean
}

let student1: IStudent = {name: "李四", age: 18, CET4: true};
let student2: IStudent = {name: "李四", age: 18, CET4: true, CET6: false};

console.log(student1);
// {name: "李四", age: 18, CET4: true}

console.log(student2);
// {name: "李四", age: 18, CET4: true, CET6: false}


4、接口的只读属性

? ? ? ? 关键字:readonly

interface IUser {
    name: string
    age: number
}

let user: IUser = {name: "张三", age: 22};
console.log(user);

// {name: "张三", age: 22}

// 接口可以继承
interface IStudent extends IUser {
    readonly DNA: string
    CET4: boolean
    CET6?: boolean
}

let student: IStudent = {name: "李四", age: 18, DNA: "aaaa", CET4: true};

console.log(student);
// {name: "李四", age: 18, CET4: true} 

// CET6是可更改的属性
student.CET6 = true;

console.log(student);
// {name: "李四", age: 18, CET4: true, CET6: true} 

// 报错 DNA字段是不可修改的,是只读属性
student.DNA = "ddddddd";


5、函数类型接口

// 接口的目的重在约束
interface IFunc {
    (name: string): void
}

let f: IFunc = (a: string): void => {
    console.log(a);
}

f("aa");

// aa

6、可索引类型接口

interface IIndex {
    [index: string]: string
}

let index: IIndex = {username: "张三", nickName: "zhangsan"};

console.log(index);

// {username: "张三", nickName: "zhangsan"}

7、类类型的接口

// 接口重在于约束
interface User {
    name: string
    age: number
    sayInfo(): void
}

class Student implements User {
    name: string
    age: number
    sayInfo(): void {
        console.log("姓名: " + this.name);
        console.log("年龄: " + this.age);
    }
    constructor(name: string, age: number) {
      this.name = name;
      this.age = age;
    }
}

let student: Student = new Student("张三", 18);
student.sayInfo();

// 姓名: 张三
// 年龄: 18

文章来源:https://blog.csdn.net/weixin_42368597/article/details/135544243
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。