patterntypescriptCritical
TypeScript and field initializers
Viewed 0 times
typescriptandinitializersfield
Problem
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 afterSolution
Update
Since writing this answer, better ways have come up. Please see the other answers below that have more votes and a better answer. I cannot remove this answer since it's marked as accepted.
Old 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:
Since writing this answer, better ways have come up. Please see the other answers below that have more votes and a better answer. I cannot remove this answer since it's marked as accepted.
Old 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 {
givenName: string;
surname: string;
}
class Person {
name: Name;
age: number;
}
var bob: Person = {
name: {
givenName: "Bob",
surname: "Smith",
},
age: 35,
};Code Snippets
interface Name {
givenName: string;
surname: string;
}
class Person {
name: Name;
age: number;
}
var bob: Person = {
name: {
givenName: "Bob",
surname: "Smith",
},
age: 35,
};Context
Stack Overflow Q#14142071, score: 119
Revisions (0)
No revisions yet.