在 TypeScript 中,当 noUncheckedIndexedAccess 标志设置为 true 时,要安全地将数组类型缩小到长度,可以在类型声明中使用 readonly
关键字,并结合 as const
达到目的。示例如下:
const arr = ['hello', 'world'] as const;
type ArrType = typeof arr;
type NarrowedArrType = ReadonlyArray & { readonly length: 2 };
function foo(arr: NarrowedArrType) {
arr.forEach((element, index) => {
console.log(`${index}: ${element.toUpperCase()}`);
});
}
foo(arr); // 输出:0: HELLO 1: WORLD
以上代码中,首先使用 as const
将数组 arr
转换为只读(readonly)类型,然后通过 typeof
获取到数组类型并赋值给 ArrType
,接着声明了一个新的类型 NarrowedArrType
,它是 ReadonlyArray
和 { readonly length: 2 }
两个类型的交叉类型。最后,我们将 arr
作为参数传递给 foo
函数,实现了安全地将数组类型缩小到长度的目的。