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
}
相关推荐
jump_jump17 小时前
用 3100 个数字造一台计算机
性能优化·架构·typescript
这是个栗子20 小时前
TypeScript(三)
前端·javascript·typescript·react
lpfasd1231 天前
TypeScript + Cloudflare 全家桶部署项目全流程
前端·javascript·typescript
行者-全栈开发1 天前
腾讯地图 Map Skills 快速入门:从零搭建 AI 智能行程规划应用
人工智能·typescript·腾讯地图·ai agent·mcp 协议·map skills·智能行程规划
梁山好汉(Ls_man)1 天前
鸿蒙_ArkTS解决Duplicate function implementation错误
开发语言·华为·typescript·harmonyos·鸿蒙
神の愛1 天前
利用json-to-ts工具进行转换,放置在typeScript.ts文件中
javascript·typescript·json
zhensherlock1 天前
Protocol Launcher 系列:Agenda 优雅组织你的想法与日程
javascript·macos·ios·typescript·node.js·mac·ipad
We་ct1 天前
LeetCode 201. 数字范围按位与:位运算高效解题指南
开发语言·前端·javascript·算法·leetcode·typescript
梁山好汉(Ls_man)1 天前
鸿蒙_关于自定义组件和自定义构建函数的个人理解
开发语言·华为·typescript·harmonyos·鸿蒙
阿珊和她的猫2 天前
TypeScript 中的 `extends` 条件类型:定义与应用
javascript·typescript·状态模式