arrays - 如何检查对象是否是 TypeScript 中的只读数组?

标签 arrays typescript typechecking

如何使用只读数组 (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/

相关文章:

javascript - 将 AngularJS 指令迁移到 Angular 2.x+ 指令作为 HTML 装饰器

字符 arr = "...";在C程序中导致崩溃

c - 使用 malloc() 分配内存块

python - readinto() 替换?

JavaScript : Rearrange array elements according to the absolute difference with x

typescript - JSDoc 中的 "T extends Component"

javascript - TypeScript 中 JavaScript 的等价物

validation - Node.js 数据访问层中的错误处理

python - 无需调用即可检查 python 函数签名

typechecking - 了解 agda 中 Unresolved 元变量和黄色突出显示