6

TypeScript version 2.4.2, compiled with --target ES6

The line of code:

var coins: { coin: number}[] = [1,1,1]

causes TypeScript to throw

error TS2322: Type 'number[]' is not assignable to type '{ coin: number; }[]'

However, the line:

var coins: { coin: number}[] = Array(3).fill(1)

compiles successfully, without errors.

Is this a TypeScript bug, or is it intended behavior (not type checking an array declared in this manner)?. If so, why?

3
  • Yeah, I don't think TS has implemented this [yet] Commented Feb 17, 2018 at 23:07
  • 1
    One of the challenges that TypeScript (or anything like that) faces is that it cannot assume that .fill() is really the stock Array.prototype.fill function. When the code runs, it could be anything. Commented Feb 17, 2018 at 23:08
  • 1
    @Pointy not really the issue here. Typescript assumes that the standard functions are not replaces by functions that have a different behavior Commented Feb 17, 2018 at 23:19

1 Answer 1

6

The problem is that Array(3) creates an array of length 3 and type any[] and then fill acts on that array. Since any can be assigned to any type, any[] can also be assigned to any other typed array (including { coin: number})

If you were to specify the type parameter for Array you would get an error:

var coins: { coin: number}[] = Array<{ coin: number}>(3).fill(1) // 1 is not assignable to { coin: number}

There is no way to prevent the omission of the type argument for the array unfortunately.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.