泛型(Generic Type)
在TypeScript中不建议使用any类型,因为这违反了TS的类型安全原则,因此我么有了泛型。 泛型简单理解就是类型变量,可以再定义时使用泛型,在使用时指定类型,下面我们来介绍一些泛型的使用方法
1. 泛型类
// 在定义类时给与泛型
class KeyValuePair<K, V> {
constructor(public key: K, public value: V) {}
}
// 初始化时固定类型
let pair1 = new KeyValuePair<number, string>(1, 'a');
let pair2 = new KeyValuePair<string, string>('1', 'a');
2. 泛型方法
function wrapInArray<T>(value: T) {
return [value]
}
let numberArr = wrapInArray(1);
let stringArr = wrapInArray('1');
3. 泛型接口
interface Result<T> {
data: T | null,
error: string | null,
}
interface User {
username: string
}
interface Product {
title: string
}
//方法使用泛型接口
function fetch<T>(url: string): Result<T> {
return {data: null, error: null}
}
//使用商品接口,所以有title属性
let result1 = fetch<Product>('url')
result1.data.title
//使用用户接口,所以有用户名属性
let result2 = fetch<User>('url')
result2.data.username
4. 类型映射
需求:创建一个相同的product接口,要求属性都是只读的
interface Product {
name: string,
price: number
}
//将product接口中的属性建立映射,同时给与readonly属性
type ReadOnlyProduct = {
readonly [k in keyof Product]: Product[k]
}
// 更进一步,可以将readonly泛型提取出来
type ReadOnly<T> = {
readonly [k in keyof T]: T[k]
}
let product:ReadOnly<Product> = {
name: 'a',
price: 1
}
// 变化 optional
type Optional<T> = {
[k in keyof T]?: T[k]
}
实际上readonly等泛型utility已经内置到ts中了,可以查阅文档
5. 工具类
5.1 Partial: Partial类型可以将已经定义好的类型中的所有字段变为可选
Interface User {
name: string;
age: number;
}
let userPartial = Partial<User> = {} // 不会报错,原属性都成为可选了
userPartial.age = 12;
5.2 Required: 与Partial相对应,将原类型中的所有字段全变成必须属性
5.3 Record: Record是用来一个确定字段类型的对象的
const nameAgeMaps: Record<string, number> = {
“Alice”: 12;
“Bob”: 13;
}
Record<string, number>等价于 {[key: string], number}
5.4 Omit: 从对象类型中移除特定的属性
interface Person {
name: string;
age: number;
location?: string;
}
const Bob: Omit<Person, ‘age’ | ‘location’> = {
name: ‘Bob’
}
5.5 Pick 只从对象中挑选特定的属性
interface Person {
name: string;
age: number;
location?: string;
}
const bob: Pick<Person, ‘name’> = {
name: ‘Bob’
};
5.6 Exclude, 从联合对象中移除类型
type Primitive = string | number | boolean;
const value: Excluede<Primitive, string> = “test”; // 会报错, 这里就不能再赋值字符串了