定义接口
interface basicResType {
code: string|number;
message?: string
}
inferface xxxResType extends basicResType{
data: object|array;
[propName: string]: string|numher|boolean
}
重载函数
巧妙利用重载函数,进入两套不同的业务代码
1.需求场景: 查找数据 => 根据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'){
}
}
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 (...) {
} else {
return cb && cb(target,orderType)
}
}
如何避免类型报错
function xxx():void{
const lArr: number[] = arguments
}
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 (
}