user2493235
user2493235

Reputation:

TypeScript Classes - Declaring an Array of Objects as a Property

I'm looking for the most appropriate way to declare an array of objects as a property when declaring a class using TypeScript. This is for use with a form that will have an unknown number of checkboxes for an Angular Template-Driven form.

Is it advisable to have a separate class for the objects, as I have below, or is there a better way? Tried searching for advice on this in many ways and can't find much. Am I way off the mark here?

export class Companion {
    id: string;
    name: string;
    chosen: boolean;
}

export class ExampleForm {
    name: string;
    email: string;
    companions: Companion[];
}

Upvotes: 2

Views: 1550

Answers (1)

frosty
frosty

Reputation: 21762

I think that most people in Typescript (not just Angular) don't use classes for these models. We use interfaces for them. So your ExampleForm would look like this.

export class ExampleForm{
    // This was what you already had
    companions: Companion[];
}

and then use an interface to define Companion.

export interface Companion{
    id: string;
    name: string;
    chosen: boolean;
}

Doing it like this will allow you to just use plain JavaScript objects for the Companions. But you will get type safety on each of those objects. It's pretty awesome.

Upvotes: 3

Related Questions