TypeScript学习第十三篇 - 泛型

在编译期间不确定变量的类型,在调用时,由开发者指定具体的类型。

1. 如何给arg参数和函数指定类型?

javascript 复制代码
function identity(arg){
    return arg;
}

identity(1)
identity('jack')
identity(true)
identity([])
identity(null)

定义的时候,无法确定类型,只有在调用的时候,才能确定参数类型。

javascript 复制代码
function identity<T>(arg:T):T{
    return arg;
}

identity<number>(1)
identity<string>('jack')

2. 多个类型如何传递?

javascript 复制代码
function identity(x,y){
    return x;
}

identity(1,2)
identity('a',2)


function identity<T,U>(x:T,y:U):T{
    return x;
}
identity<number,number>(1,2)
identity<string,number>('a',2)

回顾一下任意属性

javascript 复制代码
interface Person{
    [k:string]: string | number | boolean;
}

任意属性是不确定有什么属性,泛型是不确定有什么类型。

3. Pick的使用

Pick 就是挑选的意思,可以从已有的类型中,挑选一些类型进行使用。

javascript 复制代码
interface User{
    id: number;
    name: string;
    age: number;
}


type AgeType = Pick<User, 'age' | 'name'>

let Jack:AgeType = {
    name: 'Jack',
    age: 30
}
相关推荐
Jorah16 小时前
1. TypeScript基本语法
javascript·ubuntu·typescript
GoppViper19 小时前
uniapp中实现<text>文本内容点击可复制或拨打电话
前端·后端·前端框架·uni-app·前端开发
小白小白从不日白1 天前
TS axios封装
前端·typescript
aimmon2 天前
Superset二次开发之源码DependencyList.tsx 分析
前端·typescript·二次开发·bi·superset
下雪天的夏风2 天前
Vant 按需引入导致 Typescript,eslint 报错问题
前端·typescript·eslint
theMuseCatcher3 天前
Vue3+TypeScript+Vite+Less 开发 H5 项目(amfe-flexible + postcss-pxtorem)
typescript·less·postcss
wjs04063 天前
WebGL入门:将3D世界带入网页的魔法
javascript·3d·webgl·前端开发
Qiyandays3 天前
vue + Lodop 制作可视化设计页面 实现打印设计功能(四)
前端·vue.js·typescript
人工智能的苟富贵3 天前
微信小程序中的模块化、组件化开发:完整指南
微信小程序·小程序·typescript
Code blocks5 天前
小试牛刀-区块链Solana多签账户
算法·typescript·区块链·github