How to check if an object is a readonly array in TypeScript?

前端 未结 2 1668
清酒与你
清酒与你 2021-01-19 06:07

How to do an array check (like Array.isArray()) with a readonly array (ReadonlyArray)?

As an example:



        
相关标签:
2条回答
  • 2021-01-19 06:45

    it should be like this

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

    and test it in typescript

    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
      }
    }
    
    0 讨论(0)
  • 2021-01-19 07:01

    Here's relevant issue in typescript.

    Suggested workaround by @jcalz is adding overload to declaration of isArray:

    declare global {
        interface ArrayConstructor {
            isArray(arg: ReadonlyArray<any> | any): arg is ReadonlyArray<any>
        }
    }
    
    0 讨论(0)
提交回复
热议问题