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个回答

test
2024-07-16
感觉比较优雅的实现。
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])
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容