Ts 类型报错,能够规避吗?

function strictArray<T> (array: Array<T>) {
  return new Proxy(array, {
    get (target, p, receiver) {
      // p 报错:Element implicitly has an 'any' type because index expression is not of type 'number'.
      if (target[p] === undefined) {
        throw Error('引用下标越界')
      }

      return Reflect.get(target, p, receiver)
    }
  })
}

const arr = strictArray<number>([1, 2, 3])
console.log(arr[0])
console.log(arr[3])

阅读 1.2k
2 个回答
✓ 已被采纳

感觉比较优雅的实现。

function strictArray<T> (array: Array<T>) {
  return new Proxy(array, {
    get (target, p, receiver) {
      // 利用 in 去获取值
      if (!(p in target)) {
        throw Error('下标越界')
      }

      return Reflect.get(target, p, receiver)
    }
  })
}

const arr = strictArray<number>([1, 2, 3])
console.log(arr[0])
console.log(arr[3])

if (target[p as unknown as number] === undefined) {

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进