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
}
相关推荐
We་ct5 小时前
LeetCode 54. 螺旋矩阵:两种解法吃透顺时针遍历逻辑
前端·算法·leetcode·矩阵·typescript
We་ct7 小时前
LeetCode 36. 有效的数独:Set实现哈希表最优解
前端·算法·leetcode·typescript·散列表
Async Cipher1 天前
TypeScript 的用法
前端·typescript
We་ct1 天前
LeetCode 30. 串联所有单词的子串:从暴力到高效,滑动窗口优化详解
前端·算法·leetcode·typescript
刘联其1 天前
封装一个完整的HttpClient.ts
前端·javascript·typescript
走粥2 天前
TypeScript 泛型
开发语言·前端·javascript·windows·typescript
阿蒙Amon2 天前
TypeScript学习-第3章:复合类型
javascript·学习·typescript
踢球的打工仔2 天前
typescript-接口的基本使用(三)
前端·javascript·typescript
EndingCoder2 天前
TypeScript 最新特性:跟踪版本更新
开发语言·前端·javascript·typescript
止观止2 天前
重新认识 TypeScript:不仅仅是“带类型的 JS”
javascript·typescript