前言
本文将简要介绍Typescript一些常用泛型工具的作用以及如何使用,简单总结了一下。
Typescript泛型工具
Partial
将传入的属性变为可选项
interface IPeople {
title: string;
name: string;
}
const people: Partial<IPeople> = {
title: 'Delete inactive users'
};
Record<K, T>
类型参数K提供了对象属性名联合类型,类型参数T提供了对象属性的类型
interface Person {
name: string;
}
// 将x, y 作为Person的key
type Peoples = Record<"x" | "y", Person>;
const P: Peoples = {
x: {
name: '张三'
},
y: {
name: '李四'
}
}
Readonly
把传入的类型变为只读状态
interface Person {
name: string;
age: number;
}
const p: Readonly<Person> = {
name: '张三',
age: 22
}
p.name = '李四'; // 无法分配到 "name" ,因为它是只读属性
把传入的类型变为必填状态
interface Person {
name?: string;
age?: number;
}
const p: required<Person> = {
name: '张三',
age: 22
}
Pick<T, S>
在 T 中,过滤掉非 S 的类型
interface IPerson {
name: string;
age: number;
}
type TP = Pick<IPerson, 'name'>;
const p: TP = {
age: 22, // 对象文字可以只指定已知属性,并且“age”不在类型“TP”中
name: '张三'
}
Omit<T, K>
在 T 中删除对应的 K
interface IPerson {
name: string;
age: number;
}
type TP = Omit<IPerson, 'age'>;
const p: TP = {
name: '张三'
}
Exclude<T, U>
该工具类型能够从类型T中剔除所有可以赋值给类型U的类型
type T0 = Exclude<"a" | "b" | "c", "a">;
// 相当于 type T0 = "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
// 相当于 type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>;
// 相当于 type T2 = string | number
https://www.98891.com/article-57-1.html
Extract<T, U>
“Extract<T, U>”工具类型与“Exclude<T, U>”工具类型是互补的,它能够从类型T中获取所有可以赋值给类型U的类型
type T0 = Extract<'a' | 'b' | 'c', 'a' | 'f'>;
// 相当于 type T0 = 'a';
type T1 = Extract<string | (() => void), Function>;
// 相当于 type T1 = () => void;
type T2 = Extract<string | number, boolean>;
// 因为没有交集,相当于 type T2 = never;
ReturnType
// string
type T0 = ReturnType<() => string>;
// { a: string; b: number }
type T1 = ReturnType<() => { a: string; b: number}>;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。