如何使用只读数组 (ReadonlyArray
) 进行数组检查(如 Array.isArray()
)?
举个例子:
type ReadonlyArrayTest = ReadonlyArray<string> | string | undefined;
let readonlyArrayTest: ReadonlyArrayTest;
if (readonlyArrayTest && !Array.isArray(readonlyArrayTest)) {
// Here I expect `readonlyArrayTest` to be a string
// but the TypeScript compiler thinks it's following:
// let readonlyArrayTest: string | readonly string[]
}
对于通常的数组,TypeScript 编译器可以正确识别它必须是 if 条件内的字符串。
最佳答案
Here's typescript 中的相关问题。
@jcalz 建议的解决方法正在为 isArray
的声明添加重载:
declare global {
interface ArrayConstructor {
isArray(arg: ReadonlyArray<any> | any): arg is ReadonlyArray<any>
}
}
关于arrays - 如何检查对象是否是 TypeScript 中的只读数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56248618/