提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
typescript高阶之联合类型与交叉类型
前端必备工具推荐网站(免费图床、API和ChatAI等实用工具):
http://luckycola.com.cn/
前言
学习目标
1、联合类型与类型收缩的结合使用
2、交叉运算符特性、与交叉运算
3、工具类型.PartialByKeys的实现
4、泛型变量TKVE与显式、隐式指定
一、联合类型与类型收缩的结合使用
// 联合类型 和类型收缩
function greet(person: string | string[]): string | string[] {
if (typeof person === 'string') {
return `你好呀我是${person}返回了`
} else if (Array.isArray(person)) {
return `哈哈哈${person}`
}
throw new Error('this is error');
}
二、交叉运算符特性、与交叉运算
1.交叉运算符特性
- 唯一性: A&A等于A
- 满足交换律:A&B等价于B&A
- 满足结合律:(A&B)&C 等价于A&(B&C)
- 父类型收敛:如果B是A的父类型,则A&B将被收敛到A类型
代码如下(示例):
type PonitA = {
x: string;
y: number;
};
type PointB = {
name: string;
};
type PointC = PointB & PonitA; //{x: string;y:number;name:string}
2.交叉运算
// 复杂类型的交叉运算
type D = {
d: boolean;
}
type E = {
e: string;
}
type F = {
f: number;
}
type Test1 = {
x: D
}
type Test2 = {
x: E
}
type Test3 = {
x: F
}
type Test4 = Test1 & Test2 & Test3;// {x:{d: boolean;e: string;f:number}}
// 简单类型的交叉运算
// 简单类型的交叉运算
type Foo = {
name: string;
age: number,
color: boolean;// 注意:这里boolean可以视作由true|false两个字面量的联合类型
};
type Boo = {
name: boolean;
age: number,
color: string
};
type Fb = Foo & Boo;// never
// 函数类型的交叉运算
type F1 = (x: string, y: string) => void;
type F2 = (x: number, y: number) => void;
type F3 = F1 & F2;// (x: string | number, y: number | string) => void;
let fn: F3 = (x: string | number, y: number | string) => { };
fn('helo', 'word');//正确
//fn('helo', 1);//错误
fn(1, 2);//正确
//fn(3, 'word');//错误
// 如果希望以上错误修复可以这样
type F4 = (x: string, y: number) => void;
type F5 = (x: number, y: string) => void;
let fn2: F1 & F2 & F4 & F5 = (x: string | number, y: string | number) => { };
fn2('hello', 1);//正确
fn2(1, '222');//正确
3.PartialByKeys
功能:将一对象类型的部分key类型变成可选
思路:
1、将传入的key类型变成可选
2、pick出除了传入的这几个key之外的没有变成可选的key
3、将变成可选的和没有变成可选的交叉运算一起
// PartialByKeys
//工具类型
type PartialByKeys<T, U extends keyof T> = {
[K in U]?: T[K]
} & Pick<T, Exclude<keyof T, U>>;
type U1 = {
name: string;
age: number;
choose: boolean;
};
type U2 = PartialByKeys<U1, 'name'>;// {name?: string;age:number;choose: boolean};
let user: U2 = {
age: 11,
choose: true
};//正确
4、泛型变量TKVE与显式、隐式指定
范型变量:
T(type):表示类型
K(key):表示对象中键的类型
V(value):表示对象中值的类型
E(Element):表示元素类型
这些都是约定俗成的写法
// 显式指定泛型
function foo1<T, R>(x: T, y: R) { }
foo1<string, number>('111', 2); // function foo1<string, number>(x: string, y: number): void
// 隐式指定泛型
foo1(22, '111')// function foo1<number, string>(x: number, y: string): void