0
interface User extends Function {
    player: number,
    units: number[],
    sites: string[],
}
class User extends Function {
    constructor() {
        super('return this.player')
        [this.player, this.units, this.sites] = getBelongings(); // Destructuring Assignment
        
    }
}
const me = new User();
function getBelongings(): [number, number[], string[]] {
    return [1, [1], ['1']]
}

Playground Link

The above seems nice, and I think my assignment has no problem.

But It says: Type 'string[]' cannot be used as an index type.(2538)

I tried destructuring some times before and now have no idea about what's wrong.

Is it a TypeScript problem or a wrong syntax? And how can I make it operate well? Thanks a lot.

dbld
  • 998
  • 1
  • 7
  • 17
  • Destructuring arrays works like so : const [a, b] = myFunction() – l -_- l Jul 05 '22 at 12:00
  • please read [this answer](https://stackoverflow.com/a/38127538/19330634) – l -_- l Jul 05 '22 at 12:00
  • 1
    You need a semi colon after the call to super, or it's trying to run both statements together. The code reads as an index accessor to the return value from super, instead of a new statement. – Dave Meehan Jul 05 '22 at 12:05
  • This is weird code; you're extending `Function` and calling `super("return this.player")`. I very much doubt this will behave the way you intend at runtime, and TypeScript certainly has no idea what kind of function your instances of `User` will be. Very little of that has to do with destructuring assignment; maybe you could [edit] the question to make it a plain example of your issue, like [this](https://tsplay.dev/WJy0Rm). – jcalz Jul 05 '22 at 12:13

1 Answers1

3

You need a semi colon after the call to super, or it's trying to run both statements together.

The code, as it stands, reads as an index accessor to the return value from super, instead of a new statement.

super('return this.player');   // <-- insert semi colon
[this.player, this.units, this.sites] = getBelongings(); 
Dave Meehan
  • 3,133
  • 1
  • 17
  • 24
  • Very good point, semicolon is not the only thing that fixes this, a comma would do the same, although it has different semantics – Radu Diță Jul 05 '22 at 12:12