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])
感觉比较优雅的实现。