原生 JS 的类型
- ECMAScript 的内置对象
typescript
let b: Boolean = new Boolean(1);
let e: Error = new Error('Error occurred');
let d: Date = new Date();
let r: RegExp = /[a-z]/;
- DOM 和 BOM 的内置对象
typescript
let body: HTMLElement = document.body;
let allDiv: NodeList = document.querySelectorAll('div');
document.addEventListener('click', function (e: MouseEvent) {
// Do something
});
React
HTML 标签
react-jsx.d.ts
中定义了主要标签的类型
declare namespace JSX {
interface IntrinsicElements {
a: React.HTMLAttributes;
abbr: React.HTMLAttributes;
div: React.HTMLAttributes;
span: React.HTMLAttributes;
// ...
}
}
函数式组件
type Props = {
foo: string,
}
const MyComponent: React.FunctionComponent<Props> = props => {}
类组件
type Props = {
foo: string,
}
class MyComponent extends React.Component<Props, {}> {
// ...
}
React JSX Tip: 接收组件的实例
react 类型声明文件提供了
React.ReactElement<T>
,他可以让你通过传入<T>
来注解类组件的实例化结果。
const foo: React.ReactElement<MyComponent> = <MyComponent foo="str" />
React JSX Tip: 可渲染的接口
React 可以渲染一些像 JSX 或者 string 的内容
type Props = {
header: React.ReactNode,
}
class MyComponent extends React.Component<Props, {}> {}
<MyComponent header={<h1>Header</h1>} />
Event 事件对象类型
Event 事件对象类型
- ClipboardEvent<T = Element> 剪贴板事件对象
- DragEvent<T = Element> 拖拽事件对象
- ChangeEvent<T = Element> Change 事件对象
- KeyboardEvent<T = Element> 键盘事件对象
- MouseEvent<T = Element> 鼠标事件对象
- TouchEvent<T = Element> 触摸事件对象
- WheelEvent<T = Element> 滚轮事件对象
- AnimationEvent<T = Element> 动画事件对象
- TransitionEvent<T = Element> 过渡事件对象
事件处理函数类型
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>>;
Promise 类型
interface IResponse<T> {
message: string,
result: T,
success: boolean,
}
async function getResponse(): Promise<IResponse<number[]>> {
return {
message: '获取成功',
result: [1, 2, 3],
success: true,
}
}