文章目录加载中
Typescript-高级数据类型
# Dictionary 和 NumericDictionary
Dictionary:一个对象,键是 string 类型。
NumericDictionary:一个对象,键是 number 类型。
注意:要手动实现下,通过「索引签名」+「范型」。
定义:
interface Dictionary<T = any> {
[index: string]: T;
}
interface NumericDictionary<T = any> {
[index: number]: T;
}
使用起来:
const data2: Dictionary<number> = {
a: 3,
b: 4
};
# Record
ts 原生支持,看下它的定义:
type Record<K extends string | number | symbol, T> = { [P in K]: T };
简单来说,对于类型 Record<KEY_TYPE, VALUE_TYPE>
声明的对象,键的类型就是 KEY_TYPE,值的类型是 VALUE_TYPE。
它和直接用 interface 有啥区别? 一般 Record 可以用来做字段扩展、将值的类型转化为指定的 VALUE_TYPE、将键的类型转化为指定的 KEY_TYPE。
例子:
interface Person {
name: string
age: number
}
type PersonType = Record<'location' | keyof Person, number>
// type PersonType = {
// location: number;
// name: number;
// age: number;
}
# Pick
ts 原生支持:
type Pick<T, K extends keyof T> = { [P in K]: T[P] };
作用:将某个类型指定键挑出来,组成新的类型。
例如:
interface Student {
name: string;
age: number;
score: string;
}
type Person = Pick<Student, "age" | "name">;
// type Person = {
// age: number;
// name: string;
// }
# Exclude
ts 原生支持:
// 提取T包含在U中的类型
type Extract<T, U> = T extends U ? T : never;
作用:将联合类型中的指定类型去掉。
例如:
type NUMBERS = 0 | 1 | 2 | "a" | "b";
type CORRECT_NUMBERS = Exclude<NUMBERS, "a" | "b">; // CORRECT_NUMBERS 类型是 0 | 1 | 2
# Extract
作用:将公有属性提取出来。
例如:
type NUMBERS = 0 | 1 | 2 | "a" | "b";
type PARTIAL_NUMBERS = Extract<NUMBERS, 0 | 1>; // PARTIAL_NUMBERS 类型是 0 | 1
# 函数相关
# Parameters
作用:获取函数参数类型。
例如:
function getPerson(name: string, value?: number): any {}
type F = Parameters<typeof getPerson>; // F 类型是 [name: string, value?: number]
# ReturnType
作用:获取函数返回类型。
例如:
function getPerson(name: string, value?: number): any {}
type F = ReturnType<typeof getPerson>; // F 类型是 any
# 参考链接
本文来自心谭博客:xin-tan.com,经常更新web和算法的文章笔记,前往github查看目录归纳:github.com/dongyuanxin/blog