basarat / god-extra

Repository for issues and docs on God mode for VSCode
https://marketplace.visualstudio.com/items?itemName=basarat.god
5 stars 0 forks source link

Feature request: Generate constructor #1

Open weeco opened 6 years ago

weeco commented 6 years ago

Following up our discussion via Twitter I thought this is a better place to discuss my feature suggestion.

Desired feature (known from Visual Studio with C#): Constructor generation: https://streamable.com/xbnna Step 1: Select desired class properties which shall be initialized with the constructor Step 2: Press ctrl + . Step 3: Generate constructor

What one could do instead with TypeScript:

I am not sure what you meant at Twitter by saying you don't need a constructor at all if I use proper initializers? Did you mean something like using Partials?

class Person {
    public name: string = "default"
    public address: string = "default"
    public age: number = 0;

    public constructor(init?:Partial<Person>) {
        Object.assign(this, init);
    }
}

let persons = [
    new Person(),
    new Person({}),
    new Person({name:"John"}),
    new Person({address:"Earth"}),    
    new Person({age:20, address:"Earth", name:"John"}),
];

That wouldn't give me the strict type safety I'd like to get, hence I still believe this is a valid feature request. Maybe you can enlighten me what I am missing here, if there is a better way to solve this common constructor issue in TypeScript?