Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inconsistent length checking for tuples #27888

Closed
FrenchDilettante opened this issue Oct 13, 2018 · 2 comments
Closed

Inconsistent length checking for tuples #27888

FrenchDilettante opened this issue Oct 13, 2018 · 2 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@FrenchDilettante
Copy link

TypeScript Version: 3.1.x (and below)

Search Terms: spread length check, "bug got 0 or more"

Code

let canvasCtx: CanvasRenderingContext2D;
// Expected 4 arguments, but got 0 or more.
canvasCtx.fillRect(...[0, 0, 100, 100]);

// does not throw any error
const [x, y, w, h] = [0, 0, 100, 100];
canvasCtx.fillRect(x, y, w, h);

Expected behavior:
Being able to call a function by spreading an array, where the size of the array matches the number of requested arguments.

Actual behavior:
Typescript considers the spread to have "0 or more" elements, when it has a fixed number

Playground Link: http://www.typescriptlang.org/play/index.html#src=let%20canvasCtx%3A%20CanvasRenderingContext2D%3B%0D%0A%2F%2F%20does%20not%20work%0D%0AcanvasCtx.fillRect(...%5B0%2C%200%2C%20100%2C%20100%5D)%3B%0D%0A%0D%0A%2F%2F%20works%0D%0Aconst%20%5Bx%2C%20y%2C%20w%2C%20h%5D%20%3D%20%5B0%2C%200%2C%20100%2C%20100%5D%3B%0D%0AcanvasCtx.fillRect(x%2C%20y%2C%20w%2C%20h)%3B%0D%0A

Related Issues: #4130 [closed]

@ahejlsberg
Copy link
Member

We infer tuple types for array literals only when there is a contextual type to indicate it. For example, the following works:

let canvasCtx: CanvasRenderingContext2D;
let args: [number, number, number, number] = [0, 0, 100, 100];
canvasCtx.fillRect(...args);

In your example, since there is no indication you want a tuple type, the inferred type for the array literal is number[]. This in turn leads to the "got 0 or more" error.

Also see discussions in #16656 and #27179.

@ahejlsberg ahejlsberg added the Working as Intended The behavior described is the intended behavior; this is not a bug label Oct 13, 2018
@FrenchDilettante
Copy link
Author

Correct, thank you 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants