说明
一个完善的interface有很多优点:
- 指导业务开发人员进行对象结构解析
- 明确前后端交互结构体
- 明确属性类型
- 明确对象属性是否可为空
- 结合
eslint防止使用错方法或拼写错误
案例
下面简单列举一下常用的interface
- 基础
// 最基本props
export interface IBasicProps {
children?: ReactNode | ReactNode[]; // 子节点
}
- 路由
// 路由组件的基础props
export interface IBasicRouteCompProps<T = any> extends IBasicProps {
match: {
isExact: boolean;
params: T; // 动态路由的变量对象
path: string;
url: string;
};
location: {
hash: string;
key: string;
pathname: string;
search: string;
};
}
- Api相关
// 标准的api成功返回体
export interface ICommonRes<T = any> {
code: number;
data: T;
msg: string;
}
// 标准的api失败返回体
export interface IErrorRes {
code?: string;
message?: string;
[props: string]: any;
}
- Redux相关
import { Action, AnyAction } from 'redux';
// react-redux的dispatch希望的返回体
export interface IDispatch<A extends Action = AnyAction> {
<T extends A>(action: T): Promise<any>;
}
export interface IEffectCommand {
put: (action: AnyAction) => any;
call: (service: (data: any) => Promise<any>, payload?: object) => Promise<any>;
select: (target: (state: IConnectState) => any) => any;
take: Function;
cancel: Function;
[key: string]: any;
}
export type IEffect = (action: AnyAction, effects: IEffectCommand) => void;
export interface IDvaLoading {
global: boolean;
models: any;
effects: any;
}
export interface IConnectState {
loading: IDvaLoading; // dva-loading加载插件
// 多个model的state定义,便于获取
[key: string]: any;
}