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
}
相关推荐
用户938515635078 小时前
从零在浏览器里跑 DeepSeek-R1:WebGPU + Transformer.js 全链路实战
前端·设计模式·typescript
子兮曰12 小时前
Bun vs Node.js 深度对决:跑分快 4 倍,真实业务只剩 3%,2026 年到底该怎么选?
前端·后端·typescript
水獭比特2 天前
Agent 的 timeout 为什么会失效?把一条总预算传到底
人工智能·typescript
xcLeigh2 天前
编程语言的 AI 友好度排名:Python、JavaScript、TypeScript 谁更适合 AI 辅助
javascript·人工智能·python·ai·typescript·ai编程
谷哥的小弟2 天前
TypeScript中的any
javascript·typescript
谷哥的小弟2 天前
TypeScript在Vue3中的常见写法
前端·javascript·typescript
njsgcs2 天前
链轮 平键和键槽的标准尺寸 计算 typescript
typescript·机械工程
满栀5852 天前
请求拦截、响应拦截、业务错误统一处理
前端·typescript·anti-design-vue
谷哥的小弟2 天前
TypeScript接口
javascript·typescript
谷哥的小弟2 天前
TypeScript类型断言
前端·javascript·typescript