DDave
DDave

Reputation: 1543

Combining object destructuring with parameter properties in TypeScript

I've read about how typescript provides a shorthand where you can prefix constructor parameter with an access modifier and it is automatically declared on the class and copied from the constructor

class Foo {
    x: number;
    constructor(x:number) {
        this.x = x;
    }
}

So the previous example can be re-written as (notice public x:number):

class Foo {
    constructor(public x:number) {
    }
}

But I can't do it with a parameter with object literal:

export class Hero {
  constructor( {public id = 0   , public name = 'noname'}: {id?: number, name?: string }  = {}) {
  }
}

I get double error: error TS1005: '=' expected.

Is it possible to do it in typescript ?

Upvotes: 4

Views: 1501

Answers (1)

sasha_gud
sasha_gud

Reputation: 1735

Your specific requirement with combination of object destruction and parameter properties is not yet supported in TypeScript. See https://github.com/Microsoft/TypeScript/issues/5326 for details. But you can implement a workaround and define an interface (or class, it's not significant in TypeScript) for this puprose like this:

interface TestInterface {
    id: number;
    name: string;
}

class Greeter {
    constructor(public greeting: string, public objectField: TestInterface) {
    }

    greet() {
        return "Hello, " + this.greeting + " " + this.objectField.name;
    }
}

let greeter = new Greeter("world", { id: 0, name: 'no name' });

alert(greeter.greet());

But if you define TestInterface as class, then corresponding construcor function will be in complied JS.

var TestInterface = (function () {
    function TestInterface() {
    }
    return TestInterface;
}());

Upvotes: 1

Related Questions