【问题标题】:How to check if an object is a readonly array in TypeScript?如何检查一个对象是否是 TypeScript 中的只读数组?
【发布时间】:2019-10-08 10:59:20
【问题描述】:

如何使用只读数组 (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 条件内的字符串。

【问题讨论】:

    标签: arrays typescript typechecking


    【解决方案1】:

    Here's typescript 中的相关问题。

    @jcalz 建议的解决方法是在 isArray 的声明中添加重载:

    declare global {
        interface ArrayConstructor {
            isArray(arg: ReadonlyArray<any> | any): arg is ReadonlyArray<any>
        }
    }
    

    【讨论】:

    • 谢谢,但是我应该把接口声明放在哪里?如果我只是将其粘贴到出现问题的文件中,它将无法正常工作。
    • @mamiu 在模块内,您需要将其包装在“全局声明”中。见stackoverflow.com/questions/47130406/…
    • 太棒了!在 Github 问题上发布了这个答案。
    【解决方案2】:

    应该是这样的

    interface ArrayConstructor {
      isArray(arg: unknown): arg is unknown[] | readonly unknown[];
    }
    

    并在打字稿中测试它

    const a = ['a', 'b', 'c'];
    if (Array.isArray(a)) {
      console.log(a); // a is string[]
    } else {
      console.log(a); // a is never
    }
    
    const b: readonly string[] = ['1', '2', '3']
    
    if (Array.isArray(b)) {
      console.log(b); // b is readonly string[]
    } else {
      console.log(b); // b is never
    }
    
    function c(val: string | string[]) {
      if (Array.isArray(val)) {
        console.log(val); // val is string[]
      }
      else {
        console.log(val); // val is string
      }
    }
    
    function d(val: string | readonly string[]) {
      if (Array.isArray(val)) {
        console.log(val); // val is readonly string[]
      }
      else {
        console.log(val); // val is string
      }
    }
    
    function e(val: string | string[] | readonly string[]) {
      if (Array.isArray(val)) {
        console.log(val); // val is string[] | readonly string[]
      }
      else {
        console.log(val); // val is string
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-01
      • 2023-02-24
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 2022-10-01
      • 1970-01-01
      相关资源
      最近更新 更多