继Angular学习笔记56:TypeScript基础-- iterator和generator(next函数、return函数、throw函数),现在来看看高级类型–interface
interface 关键字可以用于描述一个对象的结构,有时候,为了复用某几个对象的结构,可能就会出现两种结构的交叉(交叉类型)或者两种结构的联合(联合类型)
有时候在项目中,描述一个用户的属性,名字,年龄,地址,电话等等这样一个对象的时候,就可以用到 interface
import {Component} from '@angular/core';
interface UserInfo {
name: string;
age: number;
address: string[];
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent {
public title = 'demo-test';
public user: UserInfo;
}
这个时候,user的就是一个UserInfo类型的属性。user的结构中有 name、age、address、这是三个属性
有时候,有两个对象结构A、B,还有一个对象结构C是A和B的合并,从而形成一个新的对象结构。
interface A {
x: string;
y: number;
z: string[];
}
interface B {
f: string;
g: number;
}
type C = A & B;
C {
x: string;
y: number;
z: string[];
f: string;
g: number;
}
但是注意,在使用交叉类型的时候,被合并的两个A、B对象结构成员属性中不能有重复,或者同一个成员变量不能有多种基本的数据类型
import {Component, OnInit} from '@angular/core';
interface UserInfo {
name: string;
age: number;
address: string[];
}
interface A {
x: string;
y: number;
z: string[];
}
interface B {
y: string;
g: number;
}
type C = A & B;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
title = 'demo-test';
user: UserInfo;
c: C;
ngOnInit(): void {
this.c.y = '1';
}
}
此时就会报错:
error TS2322: Type '"1"' is not assignable to type 'number & string'.
Type '"1"' is not assignable to type 'number'.
如果想让某一个变量有可能是number 也有可能是string时,就要用到了 联合类型
在一个函数的参数中,有时候,某一个参数的类型有可能是number又有可能是string,此时描述函数为:
function testdemo(param: string | number){
}
对于之前的报错:
error TS2322: Type '"1"' is not assignable to type 'number & string'.
Type '"1"' is not assignable to type 'number'.
如果使用 联合类型 就可以了
import {Component, OnInit} from '@angular/core';
interface UserInfo {
name: string;
age: number;
address: string[];
}
interface A {
x: string;
y: number;
z: string[];
}
interface B {
y: string;
g: number;
}
// type C = A & B;
type C = A | B;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
title = 'demo-test';
user: UserInfo;
c: C;
ngOnInit(): void {
this.c.y = '1';
this.c.x = 'demo';
}
}
此时的 y 不报错,但是x会报错:
ERROR in src/app/app.component.ts(35,12): error TS2339: Property 'x' does not exist on type 'C'.
Property 'x' does not exist on type 'B'.
因为使用了联合类型,所以类型 C 只要 A 和 B 中的交集属性。
所以此时 C 的结构如下:
C {
y: string | number;
}
所以也可以理解为: