Nickon Nickon - 4 months ago 37
TypeScript Question

TypeScript and field initializers

How to init a new class in

TS
in such a way (example in
C#
to show what I want):

// ... some code before
return new MyClass { Field1 = "ASD", Field2 = "QWE" };
// ... some code after


SOLUTION:

Classic
JavaScript
syntax:

return { Field1: "ASD", Field2: "QWE" };

Answer

There is an issue on the TypeScript codeplex that describes this: Support for object initializers.

As stated, you can already do this by using interfaces in TypeScript instead of classes:

interface Name {
    first: string;
    last: string;
}
interface Person {
    name: Name;
    age: number;
}

var bob: Person = {
    name: {
        first: "Bob",
        last: "Smith",
    },
    age: 35,
};