【问题标题】:How to represent nested array with typescript如何用打字稿表示嵌套数组
【发布时间】:2019-04-24 17:04:06
【问题描述】:

假设我有一个字符串数组,例如:

const a = ['foo', ['aa'], [['zzz',['bar']]]];
    
export const acceptsArray = (v: Array<any>) : string => {
   returns flattenDeep(v).join(' ');
};

除了使用Array&lt;any&gt; 之外,我如何表示嵌套的字符串数组?

【问题讨论】:

    标签: tsc typescript3.0


    【解决方案1】:

    解决方案

    注意仅适用于 Typescript 3.7+ 版本

    type A = 'foo' | 'aa' | 'zzz' | 'bar' | A[]
    
    const a:A = ['foo', ['aa'], [['zzz',['bar']]]];
    
    export const acceptsArray = (v: Array<A>) : string => {
       returns flattenDeep(v).join(' ');
    };
    

    谢谢

    【讨论】:

    • 这有两层深吗?我希望代表任意级别的嵌套
    • 是的,它的深度是任意的。
    【解决方案2】:

    请检查我之前写的这个实用函数。

    // NestedArray<T> represents T or Array of T or Array of Array of T .....
    // let nestedNumbers: NestedArray<number> = [[[[[1]]]]];
    export type NestedArray<T> = Array<T> | Array<NestedArray<T>>;
    
    // Able to flatten deeply nested array
    // flattenArray(nestedNumbers) should produce => [1] : Array<number>
    export const flattenArray = <T>(arr: NestedArray<T>): Array<T> => {
      if (!Array.isArray(arr)) return arr ? [arr] : [];
    
      return arr.reduce<Array<T>>((acc: Array<T>, item: NestedArray<T>) => {
        if (Array.isArray(item)) {
          return [...acc, ...flattenArray(item)];
        }
        return [...acc, item];
      }, []);
    }
    

    【讨论】:

    • 如果它总是一个数组,看起来这样会更准确吗? export type NestedArray&lt;T&gt; = Array&lt;T&gt; | Array&lt;NestedArray&lt;T&gt;&gt;;,因为这里的 T 本身不必是数组。
    猜你喜欢
    • 2020-09-28
    • 2020-03-09
    • 2022-01-03
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 2019-08-03
    • 2021-12-20
    相关资源
    最近更新 更多