any消除技巧

2020-02-11  本文已影响0人  sweetBoy_9126
  1. 数组拍平函数
function flat(arr: Array<any>): Array<any> {
  const result = []
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] instanceof Array) {
      result.push(...arr[i])
    } else {
      result.push(arr[i])
    }
  }
  return result
}
function flat<T>(arr:  Array<T | T[]>) {
  const result: T[] = []
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] instanceof Array) {
      result.push(...arr[i] as T[])
    } else {
      result.push(arr[i] as T)
    }
  }
  return result
}
  1. 类型守卫
Promise.all(newPromise).then((results: Array<[string, string]>) => {
    // results = [['username', undefined], ['password', 'too long']]
    callback(zip(results.filter<[string, string]>(item => !!item[1])))
  })

上面的代码我们filter里面接受的类型肯定是我们最后的返回值类型,而我们最后是要返回[string, string]的,但是她又说我们必须得是一个predicate,所以我们需要单独写一个类型守卫

// item有可能是[string, undefined]也有可能是[string, string],返回的这个item的类型是[string, string],然后返回item[1]的类型是string
function isError(item: [string, undefined] | [string, string]): item is [string, string] {
    return typeof item[1] === 'string'
  }
  Promise.all(newPromise).then((results: Array<[string, string]>) => {
    // results = [['username', undefined], ['password', 'too long']]
    callback(zip(results.filter<[string, string]>(isError)))
  })
上一篇下一篇

猜你喜欢

热点阅读