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
}
相关推荐
行走的陀螺仪1 天前
高级前端 Input 公共组件设计方案(Vue3 + TypeScript)
前端·javascript·typescript·vue·组件设计方案
by__csdn1 天前
微前端架构:从理论到实践的全面解析
前端·javascript·vue.js·架构·typescript·vue·ecmascript
Hao_Harrision2 天前
50天50个小项目 (React19 + Tailwindcss V4) ✨| RandomChoicePicker(标签生成)
前端·typescript·react·vite7·tailwildcss
Hao_Harrision2 天前
50天50个小项目 (React19 + Tailwindcss V4) ✨| FAQ Collapse(问题解答折叠面板)
前端·typescript·react·vite7·tailwildcss
by__csdn2 天前
javascript 性能优化实战:垃圾回收优化
java·开发语言·javascript·jvm·vue.js·性能优化·typescript
by__csdn2 天前
JavaScript性能优化:减少重绘和回流(Reflow和Repaint)
开发语言·前端·javascript·vue.js·性能优化·typescript·vue
凯小默2 天前
【TypeScript+Vue3+Vite+Vue-router+Vuex+Mock 进行 WEB 前端项目实战】学习笔记共 89 篇(完结)
typescript·echarts·mock·vue3·vite·vuex·vue-router
深兰科技2 天前
坦桑尼亚与新加坡代表团到访深兰科技,促进AI在多领域的应用落地
java·人工智能·typescript·scala·perl·ai大模型·深兰科技
今天不要写bug2 天前
vue项目基于vue-cropper实现图片裁剪与图片压缩
前端·javascript·vue.js·typescript
ttod_qzstudio2 天前
Vue 3 + TypeScript 严格模式下的 Performance.now() 实践:构建高性能前端应用
typescript·performance