2

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[];
}
5
  • 1
    This is exactly how I do it. Also, depending on your backend (if you have one) this may deserialize esaier depending what Object structure you are expecting on your form post. Commented Jul 24, 2019 at 23:32
  • Awesome, thanks, interested why it might deserialize more easily? Commented Jul 24, 2019 at 23:34
  • 1
    Why class and not just interface? Commented Jul 24, 2019 at 23:35
  • @jcalz Because I need to use it to create objects for the checkboxes? Commented Jul 24, 2019 at 23:38
  • 1
    There is an Angular Style Guide issue here which has a good discussion on the pros/cons of classes and interfaces for models. Commented Jul 24, 2019 at 23:52

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Got it, thanks, that makes sense. Knew something smelled wrong but couldn't figure it out. I'd tried companions: { id: string, name: string, chosen: boolean }[]; but TypeScript didn't like it when assigning objects. This makes much more sense, will give it a try. Thanks!
Yep, just tried it and it is indeed awesome :) Thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.