Soulzityr
Soulzityr

Reputation: 456

How to create an object and assign it to a strictly typed variable?

form: Insured: {
    firstName: response.primaryInsured.firstName,
    lastName: response.primaryInsured.lastName,
    dateofbirth: response.primaryInsured.dateOfBirth,
}

Form is part of an object, and it takes a type of Insured. The syntax here is wrong? How do I assign this new object to form?

Here is my C# equivalent I'm trying to make

form = new Insured {
    FirstName = response.FirstName,
    LastName = response.LastName
};

Upvotes: 0

Views: 42

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074266

You set the type when you declare the variable, which you haven't shown. For instance:

let form: Insured;

Then when assigning the object to it, if Insured is just a type (and you've now confirmed it is), you don't include a type at all on the assignment:

form = {
    firstName: response.primaryInsured.firstName,
    lastName: response.primaryInsured.lastName,
    dateofbirth: response.primaryInsured.dateOfBirth,
};

You can combine those:

let form: Insured = {
    firstName: response.primaryInsured.firstName,
    lastName: response.primaryInsured.lastName,
    dateofbirth: response.primaryInsured.dateOfBirth,
};

If Insured is a class constructor, you'd do:

form = new Insured(/*...arguments here...*/);

...where /*...arguments here...*/ depends on how the constructor is written. If it's written to accept the arguments in the order you've shown, then:

form = new Insured(
    response.primaryInsured.firstName,
    response.primaryInsured.lastName,
    response.primaryInsured.dateOfBirth,
);

And again, you can combine those, in which case you don't need to specify the type, TypeScript will infer it:

let form = new Insured(/*...arguments here...*/);
// or to be explicit
let form: Insured = new Insured(/*...arguments here...*/);

(you've now confirmed it's a type, not a class)

Upvotes: 1

Related Questions