typescript实用小技巧

63 阅读1分钟

定义接口

interface basicResType {
    code: string|number;
    message?: string
}
inferface xxxResType extends basicResType{
    data: object|array;
    [propName: string]: string|numher|boolean
}

重载函数

巧妙利用重载函数,进入两套不同的业务代码

1.需求场景: 查找数据 => 根据id、根据手机号、根据时间段等等
业务代码:

// id
function findDataByCustomParams(paramsType: string, cb: function, customParams1: number)
// 手机号
function findDataByCustomParams(paramsType: string, cb: function, customParams1: string)
// 时间段 (开始时间戳-结束时间戳)
function findDataByCustomParams(paramsType: string, cb: function, customParams1: number, customreParams2: number)
// 业务函数
function findDataByCustomParams(paramsType: string, cb: function, customParams1: number, customreParams2?: number){
    if (paramsType === 'id'){
        cb && cb()
    } else if (paramsType === 'phone'){
        cb && cb()
    } else if (paramsType === 'timeStamp'){
        cb && cb()
    } else if (paramsType === 'todoa'){
        // todo
    } 
}

2. 需求场景:根据排序算法类型,对数组进行排序
// 冒泡排序
function sortArrBySortType(sortType: string, orderType: string, target: array<any>)
// 自定义排序方法
function sortArrBySortType(sortType: string, orderType: string, target: array<any>, cb?:function)
function sortArrBySortType(sortType: string, orderType: string, target: array<any>, cb?:function):array<any> {
    if (sortType === 'default'){
        return target.sort((a,b)=>{
            return ordertype === 'desc' ? b-a : a-b
        })
    } else if (sortType === 'bubble'){
        return bubble(target,orderType)
    } else if (...) {
        // todo
    } else {
        return cb && cb(target,orderType)
    }
}

如何避免类型报错

// 类数组类型报错例子
function xxx():void{
    const lArr: number[] = arguments   // 提示类型错误: 当前是number[] 实际是 xxx
}

// 解决方法 
1.查看arguments的内部属性

2.用接口定义属性
interface IArgument{
 [index number]: any;
 length: number;
 callee: Function
}

3.使用新定义属性
function xxx():void{
    const lArr: IArguments = arguments   
}

枚举类型的使用技巧

1.需求场景:判断当前手机类型,跳转不同的schema(或其他)
enum phoneType {
    android
    ios
}
const data: any = { phoneType: 0} 
function jumpLink(link: string):void {
 if (
}