TypeScript中泛型与声明文件

50 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第8天,点击查看活动详情

泛型

在定义函数,接口,类的时候不能预先的确定要使用的数据的类型,而是在使用函数,接口,类的时候才能确定数据的类型

function getArr(value: T): T[] {

//const arr: T[] = [];

CONST arr: Array = [];

}

 

多个泛型参数的函数: 函数中有多个泛型的参数

function getMsg<K, V>(value: K, value1: V): [K, V] {

return [value, value1];

}

 

泛型接口

在定义接口时,为接口中的属性或方法定义泛型类型,在使用接口时,再指定具体的泛型类型

//定义一个泛型接口

interface IBaseCRUD {

data: Array

add: (t: T) => T

getUserId(id: number) => T

}

class User {

name: string,

age: number

}

//定义一个类可以针对用户的信息进行增删改查操作

class UserCRUD implements IBaseCRUD {

//用来保存多个User类型的用户对象

data: Array = []

add(user: User): User {

this.data.push(user)

return user

}

}

//实例化添加用户

userCRUD.Add(new User('zs', 10))

 

泛型类

//定义一个类,类中的属性值的类型时不确定的,方法中的参数及返回值的类型也是不确定的

//定义一个泛型类

class GenericNumber {

defaultValue: T

add(x: T, y: T) => T

}

//实例化

const g:GenericNumber = new GenericNumber();

g.defaultValue = '100';

 

泛型约束

//如果我们直接对一个泛型参数取length属性,会报错,因为这个泛型根本不知道它有这个属性

interface ILength {

length: number

}

function getLength(x: T): number {

return x.length

}

定义接口

interface Iperson {

//readonly id是只读的

readonly id: number,

name: string,

age: number,

//? 可有可无

sex?: string

}

声明文件

当使用第三方仓库时,我们需要引用它的声明文件,才能获得代码补全,接口提示等功能 声明语句: 如果需要ts对新的语法进行检查, 需要要加载了相对应的类型的代码说明 jQuery.d.ts //ts会自动解析到项目中的声明文件

declare var jQuery: (selector: string) => any;

下载声明文件 npm install @types/jquery--save-dev

//引入第三方jQuery库 import jQuery from 'jquery'; //使用jquery库 jQuery('jquery中的选择器);