Skip to content

Implicit type conversion of tuple [...T[]] to array T[] #29311

Closed
@egormkn

Description

@egormkn

TypeScript Version: 3.3.0-dev.20190108

Search Terms: spread, rest, type conversion, tuple, array length

Code

type test1 = [...number[]]           // number[]     <-- Is it a feature?
type test2 = [number, ...number[]]   // [number, ...number[]]
type test3 = [number?, ...number[]]  // [number?, ...number[]]

type fixed1 = test1 & { length: 2 }  // number[] & { length: 2 }
type fixed2 = test2 & { length: 2 }  // [number, ...number[]] & { length: 2 }
type fixed3 = test3 & { length: 2 }  // [number?, ...number[]] & { length: 2 }

let var1: fixed1 = [0, 0]
/*  error TS2322: Type 'number[]' is not assignable to type 'fixed1'.
    Type 'number[]' is not assignable to type '{ length: 2; }'.
        Types of property 'length' are incompatible.
        Type 'number' is not assignable to type '2'. */
let var2: fixed2 = [0, 0] // OK
let var3: fixed3 = [0, 0] // OK

Expected behaviour:
Expected [...number[]] and [number, ...number[]] to have the same behaviour except that the latter requires at least one element in tuple.

Actual behavior:
[...number[]] is implicitly converted to number[] with the length: number field, that is incompatible with length: 2

Error TS2322: Type 'number[]' is not assignable to type 'fixed1'.
    Type 'number[]' is not assignable to type '{ length: 2; }'.
        Types of property 'length' are incompatible.
        Type 'number' is not assignable to type '2'.

Playground Link: 🔗

Related Issues: Haven't found anything about the same problem.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: Contextual TypesThe issue relates to contextual types

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions