Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use arrays in typescript classes

I am trying to add an array as one of my class properties, but I can't seem to find out how.

This is the code that I am currently trying.

export class Foo {
    id: number;
    value: number;
    array: [];
}

I have searched online to try to find the answer with no avail, so I thought I would ask here.

like image 812
Nick Friesen Avatar asked Nov 16 '25 18:11

Nick Friesen


2 Answers

You can do it in 2 different ways based on the Typescript documentation: https://www.typescriptlang.org/docs/handbook/basic-types.html

Once you have chosen the way you want to declare you array, you have to give it a type. Example: string, number, Observable, etc.

Example 1:

export class Foo {
  id: number;
  name: string;
  array: number[]
}

Example 2:

export class Foo {
  id: number;
  name: string;
  array: Array<number>;
}
like image 196
Patricio Vargas Avatar answered Nov 19 '25 08:11

Patricio Vargas


export class Foo {
    id: number;
    value: number;
    array: Array<>;
}

if you want an Array of specific type you can use for exemple:
array: Array<string> or array: Array<number> ...

like image 35
Ayoub k Avatar answered Nov 19 '25 09:11

Ayoub k