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

Destructuring array into an object is assignable to an array type #34780

Closed
strawberry-choco opened this issue Oct 28, 2019 · 4 comments
Closed
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed

Comments

@strawberry-choco
Copy link

TypeScript Version: 3.8.0-dev.20191026

Search Terms:

  • array destructuring object
  • array destructure assign

Code

let bar = [1, 2, 3]

let foo: any[] = { ...bar }

console.log(Array.isArray(foo)) // false

Expected behavior: Typescript errors about type mismatch.

Actual behavior: Typescript does neither warn nor error about this and foo is no longer an array.

Playground Link: https://www.typescriptlang.org/play/?ts=3.8.0-dev.20191026&ssl=1&ssc=18&pln=1&pc=8#code/DYUwLgBARghgThAvBA2gRgDQQExYMwC6AUEaJAGYD2lAXBDAHYCeKBSEA3hAHS+wIBfEgGNKDAM6VQ3YJQDmACgCCcODCbcAluJVqmCqpQCURiAHozEcjGDiQQA

Related Issues: #14768

@RyanCavanaugh RyanCavanaugh added the Design Limitation Constraints of the existing architecture prevent this from being fixed label Oct 30, 2019
@RyanCavanaugh
Copy link
Member

See #9726 - TS would need a way to know that the array methods don't end up on foo.

@sebapawlak
Copy link

sebapawlak commented Aug 25, 2020

@RyanCavanaugh is this really a design limitation due to lack of enumerable properties? I believe in a very similar case for objects (not arrays) the type is correctly inferred:

class Customer {
  constructor(public name: string) {}
  greet() {
    return 'Hello ' + this.name;
  }
}
var customer = new Customer('David');
var clone = {...customer};
// console.log(clone.greet()); //Does not compile

Playground

Could we have similar feature for arrays?

@cscleison
Copy link

yeah i found that too doing a reduce and accidentally returning {...acc} instead of [...acc]. i was puzzled by why TS would be happy about it 😄

@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Dec 11, 2020

@sebapawlak TS knows which members of a class are enumerable and which aren't, but we don't have any declaration form for annotated the value-declared type of Array to provide that information. That's literally what I'm talking about re #9726

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Design Limitation Constraints of the existing architecture prevent this from being fixed
Projects
None yet
Development

No branches or pull requests

4 participants