TypeScript进阶(二) | 青训营笔记

62 阅读3分钟

这是我参与「第四届青训营 」笔记创作活动的第2天

引言

上一节我们大致学习了ts的基础知识,以及对一些基本类型,泛型的基础理解,你是否已经掌握了呢?

TypeScript 对象和接口

什么是接口

在面向对象语言中,接口(Interfaces)是一个很重要的概念,它是对行为的抽象,而具体如何行动需要由类(classes)去实现(implement)。
TypeScript 中的接口是一个非常灵活的概念,除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述。

什么是接口类型?

和number,string,boolean,enum这些数据类型一样,接口也是一种类型, 也是用来约束使用者的,他的作用是进一步定义对象内的各种属性。

先举一个简单的例子:

interface Person {
    name: string;
    age: number;
}

let tom: Person = {
    name: 'Tom',
    age: 25
};

上面的例子中,我们定义了一个接口 Person,接着定义了一个变量 tom,它的类型是 Person。这样,我们就约束了 tom 的形状必须和接口 Person 一致。
接口一般首字母大写。定义的变量比接口少了一些属性是不允许的:

interface Person { 
    name: string; 
    age: number; 
}

let tom: Person = { 
    name: 'Tom' 
};

多一些属性也是不允许的:

interface Person { 
    name: string; 
    age: number; 
} 

let tom: Person = { 
    name: 'Tom', 
    age: 25, 
    gender: 'male' 
};

可见,赋值的时候,变量的形状必须和接口的形状保持一致

可选属性

有时我们希望不要完全匹配一个形状,那么可以用可选属性:

interface Person {
    name: string;
    age?: number; //可选属性
}

let tom: Person = {
    name: 'Tom'
};

但使用可选属性的同时,我们仍然不允许在赋值的时候,添加未定义的属性

任意属性

有时候我们希望一个接口允许有任意的属性,可以使用如下方式:

interface Person {
    name: string;
    age?: number;
    [propName: string]: any;
}

let tom: Person = {
    name: 'Tom',
    gender: 'male'
};

使用 [propName: string] 定义了任意属性取 string 类型的值。
但是需要注意的是,一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集

只读属性

有时候我们希望对象中的一些字段只能在创建的时候被赋值,那么可以用 readonly 定义只读属性:

interface Person {
    readonly id: number;
    name: string;
    age?: number;
    [propName: string]: any;
}

let tom: Person = {
    id: 89757,
    name: 'Tom',
    gender: 'male'
};

tom.id = 9527;

// index.ts(14,5): error TS2540: Cannot assign to 'id' because it is a constant or a read-only property.

接口的继承

TS中的接口和JS中的类一样是可以继承的

interface LengthInterface {
  length:number
}

interface WidthInterface {
  width:number
}

interface HeightInterface {
  height:number
}

interface RectInterface extends LengthInterface,WidthInterface,HeightInterface {
  // length:number
  // width:number
  // height:number
  color:string
}

let rect:RectInterface = {
  length:10,
  width:20,
  height:30,
  color:'red'
}

函数接口

函数本质上是一个特殊的对象,我们也可以用接口来定义函数的参数和返回值。

interface SumInterface {
  (a:number, b:number):number
}

// 建议使用这种写法
let sum:SumInterface= function(x,y) {
  return x + y;
}

let res = sum(10, 20);

console.log(res);

结尾

如果我的总结对你有帮助,请给我点个赞,你的鼓励是我持续记录的一大动力~
如果文章中有错误,请多包涵,欢迎在评论中指出~