事件处理函数类型
当我们定义事件处理函数时有没有更方便定义其函数类型的方式呢?答案是使用 React 声明文件所提供的 EventHandler 类型别名,通过不同事件的 EventHandler 的类型别名来定义事件处理函数的类型。
EventHandler 类型实现源码 node_modules/@types/react/index.d.ts 。
type EventHandler<E extends SyntheticEvent<any>> = { bivarianceHack(event: E): void }["bivarianceHack"];
type ReactEventHandler<T = Element> = EventHandler<SyntheticEvent<T>>;
type ClipboardEventHandler<T = Element> = EventHandler<ClipboardEvent<T>>;
type DragEventHandler<T = Element> = EventHandler<DragEvent<T>>;
type FocusEventHandler<T = Element> = EventHandler<FocusEvent<T>>;
type FormEventHandler<T = Element> = EventHandler<FormEvent<T>>;
type ChangeEventHandler<T = Element> = EventHandler<ChangeEvent<T>>;
type KeyboardEventHandler<T = Element> = EventHandler<KeyboardEvent<T>>;
type MouseEventHandler<T = Element> = EventHandler<MouseEvent<T>>;
type TouchEventHandler<T = Element> = EventHandler<TouchEvent<T>>;
type PointerEventHandler<T = Element> = EventHandler<PointerEvent<T>>;
type UIEventHandler<T = Element> = EventHandler<UIEvent<T>>;
type WheelEventHandler<T = Element> = EventHandler<WheelEvent<T>>;
type AnimationEventHandler<T = Element> = EventHandler<AnimationEvent<T>>;
type TransitionEventHandler<T = Element> = EventHandler<TransitionEvent<T>>;
EventHandler 接收 E ,其代表事件处理函数中 event 对象的类型。
bivarianceHack 为事件处理函数的类型定义,函数接收一个 event 对象,并且其类型为接收到的泛型变量 E 的类型, 返回值为 void。
实例:
interface IProps {
onClick : MouseEventHandler<HTMLDivElement>,
}
Promise 类型
在做异步操作时我们经常使用 async 函数,函数调用时会 return 一个 Promise 对象,可以使用 then 方法添加回调函数。
Promise 是一个泛型类型,T 泛型变量用于确定使用 then 方法时接收的第一个回调函数(onfulfilled)的参数类型。
实例:
interface IResponse<T> {
message: string,
result: T,
success: boolean,
}
async function getResponse (): Promise<IResponse<number[]>> {
return {
message: '获取成功',
result: [1, 2, 3],
success: true,
}
}
getResponse()
.then(response => {
console.log(response.result)
})
我们首先声明 IResponse 的泛型接口用于定义 response 的类型,通过 T 泛型变量来确定 result 的类型。
然后声明了一个 异步函数 getResponse 并且将函数返回值的类型定义为 Promise<IResponse<number[]>> 。
最后调用 getResponse 方法会返回一个 promise 类型,通过 then 调用,此时 then 方法接收的第一个回调函数的参数 response 的类型为,{ message: string, result: number[], success: boolean} 。
Promise 实现源码 node_modules/typescript/lib/lib.es5.d.ts。
interface Promise<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
/**
* Attaches a callback for only the rejection of the Promise.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of the callback.
*/
catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
}
工具泛型使用技巧
typeof
一般我们都是先定义类型,再去赋值使用,但是使用 typeof 我们可以把使用顺序倒过来。
const options = {
a: 1
}
type Options = typeof options
使用字符串字面量类型限制值为固定的字符串参数
限制 props.color 的值只可以是字符串 red、blue、yellow 。
interface IProps {
color: 'red' | 'blue' | 'yellow',
}
使用数字字面量类型限制值为固定的数值参数
限制 props.index 的值只可以是数字 0、 1、 2 。
interface IProps {
index: 0 | 1 | 2,
}
使用 Partial 将所有的 props 属性都变为可选值
Partial 实现源码 node_modules/typescript/lib/lib.es5.d.ts
type Partial<T> = { [P in keyof T]?: T[P] };
上面代码的意思是 keyof T 拿到 T 所有属性名, 然后 in 进行遍历, 将值赋给 P , 最后 T[P] 取得相应属性的值,中间的 ? 用来进行设置为可选值。
如果 props 所有的属性值都是可选的我们可以借助 Partial 这样实现。
import { MouseEvent } from 'react'
import * as React from 'react'
interface IProps {
color: 'red' | 'blue' | 'yellow',
onClick (event: MouseEvent<HTMLDivElement>): void,
}
const Button: SFC<Partial<IProps>> = ({onClick, children, color}) => {
return (
<div onClick={onClick}>
{ children }
</div>
)
使用 Required 将所有 props 属性都设为必填项
Required 实现源码 node_modules/typescript/lib/lib.es5.d.ts 。
type Required<T> = { [P in keyof T]-?: T[P] };
看到这里,小伙伴们可能有些疑惑, -? 是做什么的,其实 -? 的功能就是把可选属性的 ? 去掉使该属性变成必选项,对应的还有 +? ,作用与 -? 相反,是把属性变为可选项。
条件类型
TypeScript2.8引入了条件类型,条件类型可以根据其他类型的特性做出类型的判断。
T extends U ? X : Y
interface Id { id: number, /* other fields */ }
interface Name { name: string, /* other fields */ }
declare function createLabel(id: number): Id;
declare function createLabel(name: string): Name;
declare function createLabel(name: string | number): Id | Name;
使用条件类型
type IdOrName<T extends number | string> = T extends number ? Id : Name;
declare function createLabel<T extends number | string>(idOrName: T): T extends number ? Id : Name;
Exclude<T,U>
从 T 中排除那些可以赋值给 U 的类型。
Exclude 实现源码 node_modules/typescript/lib/lib.es5.d.ts 。
type Exclude<T, U> = T extends U ? never : T;
实例:
type T = Exclude<1|2|3|4|5, 3|4> // T = 1|2|5
此时 T 类型的值只可以为 1 、2 、 5 ,当使用其他值是 TS 会进行错误提示。
Error:(8, 5) TS2322: Type ‘3’ is not assignable to type ‘1 | 2 | 5’.
Extract<T,U>
从 T 中提取那些可以赋值给 U 的类型。
Extract实现源码 node_modules/typescript/lib/lib.es5.d.ts。
type Extract<T, U> = T extends U ? T : never;
1
实例:
type T = Extract<1|2|3|4|5, 3|4> // T = 3|4
此时T类型的值只可以为 3 、4 ,当使用其他值时 TS 会进行错误提示:
Error:(8, 5) TS2322: Type '5' is not assignable to type '3 | 4'.
Pick<T,K>
从 T 中取出一系列 K 的属性。
Pick 实现源码 node_modules/typescript/lib/lib.es5.d.ts。
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
实例:
假如我们现在有一个类型其拥有 name 、 age 、 sex 属性,当我们想生成一个新的类型只支持 name 、age 时可以像下面这样:
interface Person {
name: string,
age: number,
sex: string,
}
let person: Pick<Person, 'name' | 'age'> = {
name: '小王',
age: 21,
}
Record<K,T>
将 K 中所有的属性的值转化为 T 类型。
Record 实现源码 node_modules/typescript/lib/lib.es5.d.ts。
type Record<K extends keyof any, T> = {
[P in K]: T;
};
实例:
将 name 、 age 属性全部设为 string 类型。
let person: Record<'name' | 'age', string> = {
name: '小王',
age: '12',
}
Omit<T,K>(没有内置)
从对象 T 中排除 key 是 K 的属性。
由于 TS 中没有内置,所以需要我们使用 Pick 和 Exclude 进行实现。
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>
实例:
排除 name 属性。
interface Person {
name: string,
age: number,
sex: string,
}
let person: Omit<Person, 'name'> = {
age: 1,
sex: '男'
}