Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Angular project : use undefined or null for properties in classes?

I've an Angular 6 project, and my question is what's the best way to define a nullable property on a model class?

Option 1 : use the ? operator

export class ProductModel {
    public name?: string;
}

Option 2 : define the property as string and as null

export class ProductModel {
    public name: string | null;
}

Note that I've set "strictNullChecks": true in the tsconfig.json.

Maybe it's just a preference, but if someone can help me providing some background tips ans tricks or a reference article?

like image 283
Stef Heyenrath Avatar asked Sep 01 '26 03:09

Stef Heyenrath


1 Answers

With strictNullChecks enabled name?: string; name is of type string | undefined.

Two examples in the question have not only slightly different syntax but also produce different results:

type WithOptional = {
    name?: string;
}

type WithNullable = {
    name: string | null;
}

const withOptional: WithOptional = {}; // no error: name is optional 
withOptional.name = null; // error: null is not assignable to string | undefined

const withNullable: WithNullable = {}; // error: name is missing
withNullable.name = undefined // error: undefined is not assingable to string | null

If you want the name to be both optional and nullable you can define it as name?: string | null;

like image 199
Aleksey L. Avatar answered Sep 02 '26 20:09

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!