搜索
写经验 领红包
 > 家居

typescipt泛型(typescipt泛型和ay的区别)

导语:TypeScript:泛型

typescript泛型(typescript泛型和any的区别)

引入

今天我们来了解一下TS中的泛型。在讲泛型前我们先来了解一个需求:创建一个函数,传入什么数据,我们就返回数据本身。

function fn(a:number):number{  return a;}

如上面代码所示,当我们已经知道函数参数类型和返回值类型时,我们可以正常的定义函数。然而,在很多时候我们无法确定函数的参数类型。这时候我们一般有两种解决办法:

第一种就是使用any。

function fn(a:any):any{  return a;}

这种虽然能够知道我们传入的参数类型,但是却无法得知返回值类型。同时,也失去了TS的类型保护机制,使得类型变得不安全。因此,我们一般不会采用它来实现上述需求,而是采用第二种方法去实现。

第二种实现方法运用到了TS这种的一个特性,叫做泛型。那么什么是泛型呢?泛型又有什么具体作用呢?

泛型

定义

泛型就是指在定义函数、接口或者类的时候,不预先指定具体类型,而是在使用的时候才指定类型限制的一种特性。

作用

泛型可以在保证类型安全的前提下,让函数等跟多种不同类型一起工作,从而实现复用。

泛型的用法

1. 泛型函数

语法
function 函数名<类型变量>(参数名:类型变量):类型变量{  ……}
实例
function fn<T>(a:T):T{  return a;}let res1 = fn<string>()let res = fn(123)  //ts中有类型推断机制可以检测泛型类型,因此可以在调用泛型函数时省略泛型类型

2. 泛型接口

语法
interface 接口名<类型变量>{……}let 变量名:接口名<类型> ;
实例
interface FullName<T>{  (firstName:T,lastName:T):T;}let getFullName:FullName<string> = (firstName,lastName) => {  return firstName + lastName}console.log(getFullName(,))

3. 泛型类

语法
interface 类名<类型变量>{……}
实例
class Animal<T>{  name:T  constructor(name:T){    this.name = name  }    action<T>(say:T){    console.log(say)  }}let cat = new Animal()cat.action()

泛型约束

在使用泛型时,我们可以通过创建一个接口,并且让泛型的类型变量extends这个接口来对泛型进行约束,从而收缩泛型类型。

语法
interface 接口名{  属性:类型;  属性:类型;  ……}function 函数名<类型变量 extends 接口名>(参数:类型变量):类型变量{  ……}
实例
interface User{  username:string;  password:string;}function login<T extends User>(args:T):T{  return args}login({username:,password:})// login({username:,password:123456}) //报错,password是string类型,不能是number// login({username:}) //报错,缺少password属性

泛型工具类型

Partial

Partial<Type>用于构建一个类型,将Type中的所有属性设置为可选。

interface Props{  id:string  children:number}type partialProps = Partial<Props>;let p1:Props = {  id:}  //报错,缺少children属性let p2:partialProps = {  id:} //不会报错,因为id和children都是可选属性
Readonly

Readonly<Type>用于构建一个类型,将Type中的所有属性设置为只读。

interface Props{  id:string  children:number}type readonlyProps = Readonly<Props>;let p1:Props = {  id:,  children:1}  let p3:readonlyProps = {  id:,  children:1}p1.children = 2p3.children = 3 //报错,因为id和children都是只读属性,无法修改
Pick

Pick<Type,Keys>从Type中选出一组属性构建新的类型。

interface Props1{  id:string  children:number  name:string}type pickProps = Pick<Props1,|>;let p4:pickProps = {  id:,  name:,  children:1} //报错,pickProps类型不含children属性let p5:pickProps = {  id:,  name:}
Record

Record<Keys,Type>用于创建一个对象类型,对象的属性键为Keys,对象的类型都为Type。

type recordProps = Record<||,string[]>let str:recordProps = {  a:[],  b:[],  c:[]}let str1:recordProps = {  a:[],  b:[]} //报错,缺少了c属性let str2:recordProps = {  a:[],  b:[],  c:} //报错,c属性的类型错误

总结

本文主要TS中的另一核心知识:泛型。通过一个简单的需求引入,接着讲解泛型在函数,接口和类中的使用。之后,学习了如何通过泛型约束来收缩泛型类型。最后,学习了TS中一些常用的泛型工具类型。

免责声明:本站部份内容由优秀作者和原创用户编辑投稿,本站仅提供存储服务,不拥有所有权,不承担法律责任。若涉嫌侵权/违法的,请反馈,一经查实立刻删除内容。本文内容由快快网络小涵创作整理编辑!