Skip to content

[Suggestion] Inferring for array literals #1007

@MaxGraey

Description

@MaxGraey

Currently all array declarations require also its type like:

let arr: i32[] = [1, 2, 3];
// or
let arr = <i32[]>[1, 2, 3]; // or as i32[]

In one hand this follow the “explicit is better than the implicit” philosophy, in other hand this complicates porting and refactoring. Even Rust has ability to infer such array literals. So will be great have a choice.

So my suggest follow next infer rule: array's element types infer from first element of array (similar to Rust). But also allow null for references in any places:

let arr1 = [1, 2, 3]                   // -> arr1: i32[]
let arr2 = [1.0, 0, 2]                 // -> arr2: f64[]
let arr3 = [0x7FFFFFFF_FFFFFFFF, 0, 1] // -> arr3: i64[]
let arr4 = [2.0 as f32, 0, 2]          // -> arr4: f32[]
let arr5 = [NaN]                       // or Infinity -> arr5: f64[]
let arr6 = ["abc", null]               // -> arr6: (string | null)[]
let arr7 = [null, "abc"]               // -> arr7: (string | null)[]
let arr8 = []                          // compile error!
let arr9 = [null]                      // compile error!
let arr10 = [1, null]                  // compile error currently. But may possible in the future
let arr11 = [1, NaN]                   // compile error!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions