ts基础应用
/*** 泛型工具类型*/
interface IProps {id: string;title: string;children: number[];
}
type omita = Omit<IProps, 'id' | 'title'>;
const omitaA: omita = {children: [1]
};
type picka = Pick<IProps, 'id' | 'title'>;
const pickaA: picka = {id: '',title: '1'
};
type partiala = Partial<IProps>;
const partialaA: partiala = {id: '1'
};
type readonlya = Readonly<IProps>;
const readonlyaA: readonlya = {id: '1',title: '1',children: [1]
};
//Record<keys,Type>构造一个对象类型,属性键为keys,属性类型为Type
type recorda = Record<'a' | 'b' | 'c', string[]>;
const recordaA: recorda = {a: ['1'],b: ['1'],c: ['1']
};/*** 泛型函数 箭头函数和普通函数*/// 箭头函数写法
const getValue = <T>(value: T): T => {return value;
};
// 声明函数写法
function getValue1<T>(value: T): T {return value;
}getValue<number>(1);
getValue1(false); //类型推断为字面量类型100// 多个参数
function getArr<K, V>(value1: K, value2: V): [K, V] {return [value1, value2];
}/*** 泛型约束* 使用extends关键字为泛型添加约束* keyof关键字获取对象所有键的集合*/
interface Ilength {length: number;
}
const getLength = <T extends Ilength>(value: T): number => {return value.length;
};const getProp = <T, k extends keyof T>(obj: T, key: k) => {return obj[key];
};
getProp({ name: 'name', age: 1 }, 'name');/*** 索引签名类型* 定义对象和数组*/interface IAnyObj<T> {[key: string]: T;
}const myObj: IAnyObj<string> = {name: 'name'
};interface IAnyArray<T> {[index: number]: T;
}const myArray: IAnyArray<number> = [1, 2];/*** 映射类型 in (keyof)* typeof*/type Person = { name: string; age: number };
type PerKeyof = keyof Person; // keyof后接类型 name | age
const per1: PerKeyof = 'age';const person: Person = { name: 'name', age: 1 };
type PerTypeof = typeof person; // typeof后接具体对象
const per2: PerTypeof = { name: 'name', age: 1 };
// 用法1: 根据联合类型创建新类型
type PropKeys = 'x' | 'y' | 'z'; // const a: PropKeys = 'x';
// 等价于{x:string;y:string;z:string} 三个属性都包含
type types = { [key in PropKeys]: string };
const typesObj: types = {x: '1',y: '1',z: '1'
};
// 用法2: 根据对象类型创建新类型
type PropsObj = { a: number; b: string; c: boolean };
type Type1 = { [key in keyof PropsObj]: PropsObj[key] };
const Type1Obj: Type1 = {a: 1,b: '1',c: true
};// 泛型工具partial是根据映射类型实现的
type MyPartial<T> = {[key in keyof T]?: T[key];
};
type MyPartialA = {name: string;age: number;phone: number;
};
const MyPartialAObj: MyPartial<MyPartialA> = {name: '1'
};
// 注意区分和in keyof的区别
const MyPartialAObj1: { [p in keyof MyPartialA]: MyPartialA[p] } = {name: '1' // 类型“{ name: string; }”缺少类型“{ name: string; age: number; phone:
};
当在公司axios严格使用ts
和后端定义好接口返回参数,使用泛型定义好核心data结构
AxiosResponse是axios返回的一个类型,带一个泛型参数T,属性有config,headers,request,status,statusText和data属性,其中data接受泛型T
// /api/index.ts
import axios, { AxiosResponse } from 'axios';
import config from '@/utils/config';
// 定义接口返回失败参数类型
interface ErrorResponse {error_code: string;error_message: string;
}// 定义接口返回成功参数类型
interface AxiosHomeResponse<T = any> {data: T;stateCode?: {code?: string;desc?: string;};statusText?: string;success?: boolean;
}
export type BaseResponse<T> = Promise<AxiosResponse<T>>;// 封装接口返回参数类型
export type HomeResponse<T> = BaseResponse<AxiosHomeResponse<T> & ErrorResponse>;
/*** 设置全局配置*/
axios.defaults.withCredentials = true;
axios.defaults.validateStatus = (status: number) => {return status >= 200 && status < 599;
};export const createAxios = (baseURL: string) => {const instance = axios.create({ baseURL });instance.interceptors.request.use((config) => {if (config.method?.toLocaleLowerCase() === 'get') {config.params = { ...config.params, _: Date.now() };}return config;},(error) => {// 对请求错误做些什么return Promise.reject(error);});instance.interceptors.response.use((response) => {// 对响应数据做点什么switch (response.status) {case 401:// 跳转登陆页面break;}return response;},(error) => {// 对响应错误做点什么if (error.response && error.response.data) {// 弹出统一错误提示}return Promise.reject(error);});return instance;
};// test接口
/*** url: http://localhost:3001/api* 不同环境的url可以抽离到config下的配置文件 todo...* 不同模块的请求域名可以各自配置*/
export const homeApi = createAxios('http://localhost:3001/api');
在文件夹api中分模块定义请求接口和ts类型
// /api/home/index.ts
import { homeApi, HomeResponse } from '..';
import * as Types from './type';// 拿到接口返回的res就有ts类型提示了
export const getHome = (params: Types.IHomeParams): HomeResponse<Types.IHomeRes[]> => {return homeApi.post('/home', { params });
};
// /api/home/type.ts
export interface IHomeParams {id: number;
}export interface IHomeRes extends IHomeParams {msg: string;
}
在请求结果中就会有对应的提示了