接口的使用
如果我们有一个函数,这个函数接受一个 person 对象,然后返回它的某个属性,这时会发现它报错了:
image.png
我们必须用一种类型描述这个参数,但是这个类型又不属于各种基本类型,这个时候我们需要接口
interface
来描述:
interface Person{
name: string;
age: number;
}
const getName = (person: Person) => person.name;
可选属性:
interface Person{
name: string;
age?: number;
}
const getName = (person: Person) => person.name;
console.log(getName({name: "haha"}));
只读属性
interface Person{
name: string;
age?: number;
readonly isMale: boolean;
}
只读属性只能在对象刚刚创建的时候修改其值
函数
一般是在接口内部描述函数:
interface Person{
name: string;
age?: number;
readonly isMale: boolean;
say: (words: string) => string;
}
或者先用接口描述函数类型:
interface Say {
(words: string) : string;
}
interface Person{
name: string;
age?: number;
readonly isMale: boolean;
say: Say;
}
额外的属性检查
interface SquareConfig {
color?: string;
width? : number;
}
function getSquare(config: SquareConfig): { area: number }{
...
}
getSquare({ width: 10, height: 5 }); //Error
当我们传入了一个任何“目标类型”都不包含的属性height
时,会触发额外的属性检查,并报出一个错误。
绕开这些检查有三种方法:
- 使用类型断言
getSquare({ width: 10, height: 5 } as SquareConfig );
- 添加一个字符串索引签名
interface SquareConfig {
color?: string;
width?: number;
[proName:string]: any;
}
getSquare({ width: 10, height: 5, opacity: 1 });
这表示的是SquareConfig
可以有任意数量的属性,并且只要它们不是color和width,那么就无所谓它们的类型是什么。
- 将字面量赋值给另外一个变量
interface SquareConfig {
color?: string;
width? : number;
}
function getSquare(config: SquareConfig): { area: number }{
...
}
let params = {
width: 10,
height: 5,
opacity: 1
}
let square = getSquare(params)
本质上是转化为 any
类型,一般不建议采用这种方法。
可索引的类型
interface stringArray{
[index: number] : string
}
let arr1: stringArray = [1,2,3]; // Error
let arr2: stringArray = ["1","2","3"]; // OK
interface User {
[name: string]: number;
}
let ages: User = {
"dingdabao": 25,
"lubenwei": 30
}
接口继承
interface Animal {
height: number;
weight: number;
}
interface People {
name: string;
age: number;
}
//接口支持多继承
interface Student extends People,Animal {
study: () => void;
}