VansFannel
VansFannel

Reputation: 45921

Set a Typescript array as undefined

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[]'.

Upvotes: 4

Views: 12002

Answers (3)

Tom Fenech
Tom Fenech

Reputation: 74595

undefined is its own type, so you would need to change your declaration to:

public products: IProduct[]?; // optional property
// or
public products: IProduct[] | undefined; // explicit intersection with undefined 

Now that products isn't necessarily an array, you need to use a type guard before treating it as an array. We don't need to write our own, as we can use instanceof Array, which is recognised by TypeScript as a type guard:

if (this.products instanceof Array) {
    // use this.products as an array
}

Alternatively, you can set strictNullChecks to false (either by removing the compiler switch --strictNullChecks, or in your tsconfig.json), so that null or undefined are permitted values of every type. Personally I would recommend against doing this, and trying to handle possible nulls and undefineds on a case-by-case basis.

Upvotes: 1

Meirion Hughes
Meirion Hughes

Reputation: 26398

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

Upvotes: 9

Ali Turab Abbasi
Ali Turab Abbasi

Reputation: 1133

Just don't assign any value to it and it will remain undefined.

public products: IProduct[];

Upvotes: 0

Related Questions