Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a Typescript array as undefined

Tags:

typescript

I'm developing an Angular 2 application. This the first time I do something with Angular or Typescript.

I have this variable inside of a class:

public products: IProduct[];

IProduct is:

interface IProduct {
    productCode: string;
    description: string;
    lawId: number;
    name: string;
    comment: string;
    emvoProduct?: IEmvoProduct; // ?: Optional.
}

Is there any way to set it to undefined?

When I do this:

this.products = undefined;

I get an error saying:

(TS) Type 'undefined' cannot be converted to type 'IProduct[]'.

like image 341
VansFannel Avatar asked Oct 19 '25 16:10

VansFannel


1 Answers

Its because of strictNullChecks compile option in your tsconfig.json; you can simply remove or set to false.

Alternatively, you have to specify that the field can be undefined:

products: IProduct[] | undefined

Another alternative is to delete

delete this.products

this will truly make the field undefined when you check for it because its simply not there. typescript will be happy with it -- even with strictNullCheck: true

like image 174
Meirion Hughes Avatar answered Oct 21 '25 08:10

Meirion Hughes