Typescript Array vs any[]

后端 未结 2 708
半阙折子戏
半阙折子戏 2020-12-14 07:18

In TypeScript, what is the difference between Array and any[]? Does Array refer to dynamically sized arrays (during compile-time, of course) and

相关标签:
2条回答
  • 2020-12-14 07:36

    Spec section 3.5.4 specifies their relationship:

    An array type of the form ElementType[] is equivalent to an object type with the index signature [index: number]: ElementType plus a set of members equivalent to the global interface type Array where all occurrences of the magic _element type are replaced with ElementType.

    Not being able to assign [[], []] or [] to Array is a bug.

    There is no notion of a "statically-sized" array in TypeScript. They're all talking about the same underlying JavaScript array (which is dynamically sized):

    var x = [1, 2];
    x.push(3);
    x[13] = 5;
    
    0 讨论(0)
  • 2020-12-14 07:52

    The previous answer to this question has been outdated for a while now.

    First of all Array requires a generic parameter:

    var arr: Array<any>;
    

    This is equivalent to:

    var arr: any[];
    

    Types Array<any> and any[] are identical and both refer to arrays with variable/dynamic size.

    Typescript 3.0 introduced Tuples, which are like arrays with fixed/static size, but not really.

    Let me explain.

    Their syntax looks like this:

    var arr: [any];
    var arr: [any, any];
    var arr: [any, any, any];
    var arr: [string, number, string?, MyType];
    

    Typescript will force you to assign an array of that length and with values that have the matching types.
    And when you index the array typescript will recognize the type of variable at that index.

    It's interesting to note that typescript wont stop you from modifying the size of the Tuple, either by using a function like .push() or by assigning a value to length. So you have to make sure you don't do it by accident.

    You can also specify a "rest" type for any extra elements:

    var arr: [any, any, ...any[]];
    var arr: [string, number, string?, MyType, ...YourType[]];
    

    In which case you can assign more items to the Tuple and the size of the array may change.

    Note: You can not assign a normal array to a Tuple.

    In case you only specify a rest type, then you get a regular old array.
    The following 2 expressions are equivalent:

    var arr: [...any[]];
    var arr: any[];
    
    0 讨论(0)
提交回复
热议问题