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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With