TypeScript进阶知识之接口(接口定义、接口属性、可索引类型、接口表示函数类型、额外的属性检查、接口继承、接口与类型别名的区别)

您所在的位置:网站首页 free函数的参数类型 TypeScript进阶知识之接口(接口定义、接口属性、可索引类型、接口表示函数类型、额外的属性检查、接口继承、接口与类型别名的区别)

TypeScript进阶知识之接口(接口定义、接口属性、可索引类型、接口表示函数类型、额外的属性检查、接口继承、接口与类型别名的区别)

2024-07-11 05:15| 来源: 网络整理| 查看: 265

系列文章目录

引入一:Typescript基础引入(基础类型、元组、枚举) 引入二:Typescript面向对象引入(接口、类、多态、重写、抽象类、访问修饰符) 第一章:Typescript基础知识(Typescript介绍、搭建TypeScript环境、基本数据类型) 第二章:Typescript常用类型(任意值any、数组Array、函数Function、元组Tuple、类型推论、联合类型) 第三章:Typescript基础知识(类型断言、类型别名、字符串字面量类型、枚举、交叉类型) 第四章:Typescript基础知识(类型拓宽、类型缩小) 第五章:TypeScript进阶知识之类(类的定义、类的基本使用、类的构造函数、类的属性和方法、访问修饰符、类的继承、抽象类) 第六章:TypeScript进阶知识之接口(接口定义、接口属性、可索引类型、接口表示函数类型、额外的属性检查、接口继承、接口与类型别名的区别) 第七章:TypeScript进阶知识之泛型(泛型的定义、为什么要使用泛型、泛型的使用、泛型变量、多个类型参数、泛型类、泛型接口、泛型参数默认类型、泛型约束)

文章目录 系列文章目录一、接口定义二、接口属性2.1 可选属性2.2 只读属性2.3 任意属性 三、可索引类型四、接口表示函数类型五、额外的属性检查5.1 什么是额外的属性检查5.2 绕开额外的属性检查 六、接口相关的继承6.1 类实现接口6.2 接口继承接口6.3 接口继承类 七、接口与类型别名的区别7.1 相同点7.1.1 类型别名和接口都支持扩展。7.1.2 类型别名和接口都可以定义对象和函数。 7.2 不同点7.2.1 接口使用 interface 关键字定义,类型别名使用 type 关键字定义。7.2.2 同名的接口会自动合并,而同名的类型别名不行。7.2.3 类型别名可以用于基本类型、联合类型和元组类型的定义,而接口只能用于描述对象的形状和行为。7.2.4 接口可以被类实现(implements),用来约束类的结构和行为,而类型别名不能。 7.3 使用场景

一、接口定义

TypeScript 中,接口(Interface)是一种用来定义对象的结构和行为的类型。通过接口,我们可以定义对象应该有哪些属性、属性的类型以及方法。

使用关键字 interface 来定义接口。声明接口后,直接使用接口名称作为变量的类型。方法的定义和函数的定义类似,包括参数和返回值类型。 二、接口属性 2.1 可选属性

带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个 ? 符号。

interface Person { name: string; age?: number; // 可选属性 } const p1: Person = { name: "Alice" }; const p2: Person = { name: "Bob", age: 25 };

可选属性的好处有2个:

可以对可能存在的属性进行预定义可以捕获引用了不存在的属性时的错误 2.2 只读属性

有时候我们希望某些属性在对象创建后不能被修改,可以将这些属性声明为只读属性。

通过在属性名称前面加上 readonly 关键字,就可以将属性设置为只读。

interface Point{ readonly x:number, readonly y:number, } let point:Point={ x:10, y:20, } point.x=100;// Error:Cannot assign to 'x' because it is a read-only property.

上述例子中,声明了一个Point的接口,接口中的属性 x 和 y 都是只读的,然后创建了一个 point 对象,类型为 Point,此时,我们不能再给对象中的 x 和 y 重新赋值,会报错,因为它们都是只读属性。

TypeScript 还提供了 ReadonlyArray 类型,它与 Array 相似,只是把所有可变方法去掉了,确保数组创建后再也不能被修改。

let a:number[]=[1,2,3]; let a2:ReadonlyArray=a; a2[0]=100;//Error:Index signature in type 'readonly number[]' only permits reading. 2.3 任意属性

一个接口中除了包含必选和可选属性之外,还允许有其他的任意的属性,这时我们可以使用 索引签名 的形式来满足上述要求。

interface Person{ name:string, age?:number,//Error:Property 'age' of type 'number | undefined' is not assignable to 'string' index type 'string'. [propName:string]:string, } let p:Person={ name:'Tom', age:25, gender:'male', location:'Shanghai' }

上述例子中,任意属性的值允许是 string,但是可选属性 age 的值却是 number,number 不是 string 的子属性,所以报错了。

注意1:一旦定义了任意属性,那么必选属性和可选属性的类型都必须是它的类型的子集

注意2:一个接口中只能定义一个任意属性。如果接口中有多个类型的属性,则可以在任意属性中使用联合类型。

interface Person { name: string; age?: number; // 这里age真实的类型应该为:number | undefined [propName: string]: string | number | undefined; } let person: Person = { name: 'Echo', age: 25, gender: 'male' } 三、可索引类型

接口可以描述具有索引签名的对象,这样我们就可以通过索引来访问对象的属性。

interface StringArray { [index: number]: string; } let myArray: StringArray = ["Bob", "Fred"]; let myStr: string = myArray[0];//Bob

TypeScript 支持两种索引签名:字符串和数字。可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。 这是因为当使用 number 来索引时,JavaScript 会将它转换成 string 然后再去索引对象。 也就是说用 100(一个number)去索引等同于使用"100"(一个string)去索引,因此两者需要保持一致。

四、接口表示函数类型

使用接口表示函数类型,我们需要给接口定义一个调用签名。 它 就像是一个只有参数列表和返回值类型的函数 定义,参数列表里的每个参数都需要名字和类型。

interface Fun{ (name:string,age:number):string }

在上述例子中,Fun是一个接口,它表示一个接收两个参数 number 和 age,参数类型都为 string,并且返回值为 string 类型的函数。这样定义后,我们可以像使用这个接口定义函数类型的变量了。

下面的例子创建一个函数类型的变量,并将一个同类型的函数赋值给这个变量。

interface Fun{ (name:string,age:number):string } const fun:Fun=(name:string,age:number)=>{ return name + ' is ' + age + ' years old'; }

注意:对于函数类型的类型检查来说,函数的参数名不需要与接口里定义的名字相匹配。

interface Fun{ (name:string,age:number):string } const fun: Fun = (n: string, a: number) => { return n + ' is ' + a + ' years old'; };

函数的参数会逐个进行检查,要求对应位置上的参数类型是兼容的。

如果不想指定类型,TypeScript 的类型系统会推断出参数类型,因为函数直接赋值给了 Fun 类型变量。函数的返回值类型是通过其返回值推断出来的

interface Fun{ (name:string,age:number):string } const fun: Fun = (n, a) => { return n + ' is ' + a + ' years old'; };

对象里面通常有函数方法,同样也可以在接口里面定义,在接口里定义的函数参数、返回值,在使用的时候必须按照约束传入。

interface Person { name: string; age: number; say: (message: string) => void; } let p: Person = { name: 'Tom', age: 25, say: (message: string) => { console.log(message); }, }; p.say('hello');//hello 五、额外的属性检查 5.1 什么是额外的属性检查

当我们使用对象字面量赋值给接口类型时,TypeScript 会自动进行额外的属性检查。这意味着赋值的对象不能包含接口中未定义的额外属性,否则会导致编译错误。

interface Person { name: string; } let p:Person = { name: 'Tome', age: 25 };//Error 5.2 绕开额外的属性检查

鸭式辨型法 就是通过制定规则来判定对象是否实现这个接口。

interface Person { name: string; } // let p:Person = { name: 'Tome', age: 25 }; function printName(person: Person) { console.log(person.name); } let p = { name: 'Tome', age: 25 }; printName(p); printName({ name: 'Tome', age: 25 });//Error

上面代码,在参数里写对象就相当于是直接给person赋值,这个对象有严格的类型定义,所以不能多参或少参。而当你在外面将该对象用另一个变量p接收,p不会经过额外属性检查,但会根据类型推论为let p: { name: string; age: number} = { name: 'Tome', age: 25 };,然后将这个p再赋值给person,此时根据类型的兼容性,两种类型对象,参照鸭式辨型法,因为都具有name属性,所以被认定为两个相同,故而可以用此法来绕开多余的类型检查。

类型断言 类型断言的意义就等同于你在告诉程序,你很清楚自己在做什么,此时程序自然就不会再进行额外的属性检查了。

interface Person{ name:string, age:number, money?:number } let p1:Person={ name:'Tom', age:25, money:100, sex:0, } as Person

索引标签

interface Person{ name:string, age:number, money?:number, [key:string]:any, } let p2:Person={ name:'Tom', age:25, money:100, sex:0, } 六、接口相关的继承 6.1 类实现接口

实现(implements)是面向对象中的一个重要概念。一般来讲,一个类只能继承自另一个类,有时候 不同类之间可以有一些共有的特性,这时候就可以把特性提取成接口(interfaces),用 implements 关键字来实现。

举例:门是一个类,防盗门是门的子类。如果防盗门有一个报警器的功能,我们可以给防盗门添加一个报警方法。这时候如果有另一个类,车,也有报警器的功能,就可以考虑把报警器提取出来,作为一个接口,防盗门和车都去实现它。

interface Alarm { alert(): void; } class Door { } class SecurityDoor extends Door implements Alarm { alert() { console.log('SecurityDoor alert'); } } class Car implements Alarm { alert() { console.log('Car alert'); } }

一个类可以实现多个接口。就好比一个车不只有报警功能,还有开关车灯的功能:

interface Alarm { alert(): void; } interface Light { lightOn(): void; lightOff(): void; } class Car implements Alarm, Light { alert() { console.log('Car alert'); } lightOn() { console.log('Car light on'); } lightOff() { console.log('Car light off'); } } 6.2 接口继承接口

接口与接口之间可以是继承关系,A接口要继承B接口的属性,可以通过extends关键字继承。

通过继承,子接口可以获得父接口中定义的属性和方法,并可以在自身接口中添加新的属性和方法。

interface Shape { color: string; } interface Circle extends Shape { radius: number; getArea(): number; } const circle: Circle = { color: "red", radius: 5, getArea() { return Math.PI * this.radius * this.radius; } }

在上面的例子中,使用 extends 关键字实现了接口 Circle 继承 Shape。继承后,Circle 就有了 Shape 中的 color 属性,以及自身的 radius 属性以及 getArea() 方法。

6.3 接口继承类

常见的面向对象语言中,接口是不能继承类的,但是在 TypeScript 中却是可以的:

class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } interface Point3d extends Point { z: number; } let point3d: Point3d = {x: 1, y: 2, z: 3};

实际上,当我们在声明 class Point 时,除了会创建一个名为 Point 的类之外,同时也创建了一个名为 Point 的类型(实例的类型)。

所以我们既可以将 Point 当做一个类来用(使用 new Point 创建它的实例):

class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } const p = new Point(1, 2);

也可以将 Point 当做一个类型来用(使用 : Point 表示参数的类型):

class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } function printPoint(p: Point) { console.log(p.x, p.y); } printPoint(new Point(1, 2));

这个例子实际上可以等价于:

class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } interface PointInstanceType { x: number; y: number; } function printPoint(p: PointInstanceType) { console.log(p.x, p.y); } printPoint(new Point(1, 2));

上例中我们新声明的 PointInstanceType 类型,与声明 class Point 时创建的 Point 类型是等价的。

所以回到 Point3d 的例子中,我们就能很容易的理解为什么 TypeScript 会支持接口继承类了:

class Point { x: number; y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } interface PointInstanceType { x: number; y: number; } // 等价于 interface Point3d extends PointInstanceType interface Point3d extends Point { z: number; } let point3d: Point3d = {x: 1, y: 2, z: 3};

上述案例中,当我们声明 interface Point3d extends Point 时,Point3d 继承的实际上是类 Point 的实例的类型。

所以「接口继承类」和「接口继承接口」没有什么本质的区别。

值得注意的是,PointInstanceType 相比于 Point,缺少了 constructor 方法,这是因为 声明 Point 类时创建的 Point 类型是不包含构造函数的。另外,除了构造函数是不包含的,静态属性或静态方法也是不包含的(实例的类型当然不应该包括构造函数、静态属性或静态方法)。

换句话说,声明 Point 类时创建的 Point 类型只包含其中的实例属性和实例方法:

class Point { /** 静态属性,坐标系原点 */ static origin = new Point(0, 0); /** 静态方法,计算与原点距离 */ static distanceToOrigin(p: Point) { return Math.sqrt(p.x * p.x + p.y * p.y); } /** 实例属性,x 轴的值 */ x: number; /** 实例属性,y 轴的值 */ y: number; /** 构造函数 */ constructor(x: number, y: number) { this.x = x; this.y = y; } /** 实例方法,打印此点 */ printPoint() { console.log(this.x, this.y); } } interface PointInstanceType { x: number; y: number; printPoint(): void; } let p1: Point; let p2: PointInstanceType;

上例中最后的类型 Point 和类型 PointInstanceType 是等价的。同样的,在接口继承类的时候,也只会继承它的实例属性和实例方法。

七、接口与类型别名的区别 7.1 相同点 7.1.1 类型别名和接口都支持扩展。

类型别名的扩展 是通过 交叉操作符(&) 来实现的。

type Person = { name: string; age: number; }; type User = Person & { gender: string; city: string; }; const user: User = { name: 'Echo', age: 26, gender: 'Male', city: 'Guang Zhou', };

接口的扩展 是通过 extends 来实现的。

interface Shape { color: string; getArea(): number; } interface Circle extends Shape { radius: number; } const circle: Circle = { color: 'red', radius: 5, getArea:()=>{ return Math.PI * this.radius * this.radius; } } console.log(circle.getArea()); // 输出:314.1592653589793 7.1.2 类型别名和接口都可以定义对象和函数。

使用接口定义对象和函数

interface Point2D { x: number; y: number; } const point2D: Point2D = { x: 100, y: 200, }; console.log(point2D.x, point2D.y); // 输出:100 200 interface MathOperation { (x: number, y: number): number; } const add: MathOperation = (x, y) => x + y; console.log(add(100, 200)); // 输出:300

使用类型别名定义对象和函数

type Point2D = { x: number; y: number; } const point2D: Point2D = { x: 100, y: 200, }; console.log(point2D.x, point2D.y); // 输出:100 200 type MathOperation = (x: number, y: number) => number; const add: MathOperation = (x, y) => x + y; console.log(add(100, 200)); // 输出:300 7.2 不同点 7.2.1 接口使用 interface 关键字定义,类型别名使用 type 关键字定义。 interface Person { name: string; age: number; } type Person2 = { name: string; age: number; } 7.2.2 同名的接口会自动合并,而同名的类型别名不行。

当 声明了多个同名的接口 时,TypeScript会将它们的 属性、方法等成员进行合并 ,并形成一个 包含了所有成员的合并接口。

interface Person { id: number; name: string; } interface Person { age: number; } const person: Person = { id: 1, name: 'Echo', age: 26, }

而 如果在同一个作用域中定义了多个同名的类型别名,TypeScript 会报错:提示多次定义了同一个类型别名。 这是因为类型别名的定义是直接为现有类型起一个别名,无法进行合并。

7.2.3 类型别名可以用于基本类型、联合类型和元组类型的定义,而接口只能用于描述对象的形状和行为。 type MyString = string; type MyNumber = number; type MyBoolean = boolean; const username: MyString = 'Echo'; const age: MyNumber = 26; const isMale: MyBoolean = true; type MyType = string | number | boolean; const username: MyString = 'Echo'; const age: MyNumber = 26; const isMale: MyBoolean = true; type Point2D = [number, number]; const p1: Point2D = [1, 2]; // 有效的元组 const p2: Point2D = [3, 4]; // 有效的元组 const p3: Point2D = [5, 6, 7]; // 编译错误:不能将类型“[number, number, number]”分配给类型“Point2D”。源具有 3 个元素,但目标仅允许 2 个。ts(2322) const p4: Point2D = [8]; // 编译错误:不能将类型“[number]”分配给类型“Point2D”。源具有 1 个元素,但目标需要 2 个。 7.2.4 接口可以被类实现(implements),用来约束类的结构和行为,而类型别名不能。

接口可以被类实现,用来约束类的结构和行为。通过实现接口,类必须满足接口中定义的属性和方法要求。

interface Animal { name: string; makeSound(): void; } class Dog implements Animal { name: string; constructor(name: string) { this.name = name; } makeSound(): void { console.log('Woof!'); } } const dog = new Dog('Buddy'); dog.makeSound(); // 输出: 'Woof!' 7.3 使用场景

使用接口的一些场景:

描述对象的形状和结构:如果需要定义一个具有特定属性和方法的对象结构,接口是更适合的选择。接口可以明确指定每个属性的类型和方法的签名。类的实现。继承其它接口。

使用类型别名的一些场景:

为现有类型起别名。定义联合类型、交叉类型或其它复杂类型。表示函数类型


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3