简体   繁体   中英

Syntax Error on Destructuring Assignment in TypeScript

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.

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM