Tips and Tricks in a world of Mix

Posts tagged ‘init’

Init type instance in Typescript 2.1 automatically – loved it !

So simple and elegant :

Found in this post

 

Typescript 2.1 introduces Mapped Types and provides Partial<T>, which allows you to do this….

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"}),
];
 
Advertisements

Tag Cloud

%d bloggers like this: