Combining object destruction with parameters in TypeScript

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

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

      

So the previous example can be rewritten as (public x: number notice):

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

      

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

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

      

I am getting double error: error TS1005: '=' expected.

Is it possible to do this in typescript?

+3


source to share


1 answer


Your specific requirement with a 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 a class not irrelevant 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 a class, then the corresponding construcor function will be executed in JS.

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

      

0


source







All Articles