简体   繁体   中英

Angular Typescript: Assigning class members null or Union Type Operator Difference

Whats the difference between assigning things null, or giving Union type operator null. Either way, both data types allow class member to be null, so would like to understand. Is there a difference in behavior?

export class PropertyAddress {
    city?: string = null;
    state?: string = null;
    zipcode?: string = null;


export class PropertyAddress {
    city?: string | null;
    state?: string | null;
    zipcode?: string | null;

Background of question:

Wanted to declare a class, and ensure all members exist and start out as null, if Nothing is defined. Had an issue where class members were not appearing in debugger, if they were not preset –

It is a TypeScript thing.

The following line

city?: string = null;

means that you declared an attribute city of type string and initialized it with value null . In this case, if you set --strictNullChecks flag as true in its config then it will throw an error.

On the other hand, the following line

city?: string | null

means that you declared an attribute city of type string or null and you can make city value as null even with the --strictNullChecks flag set as true .

For More info - check out TypeScript 2.0 release notes .

In fact,null is assignable to any type.If your property type is string,number or a class you can pass a null into them.But what is difference between these two property:

class test{
    city?: string | null;
    city2?: string = null;
}

If you make an instance of test class, the value of city would be undefined, but the value of city2 is null.

  1. city?: string = null;
    City's type here is string, and you initialised it as null.
  2. city?:string | null;
    We use the vertical bar (|) to separate each type, so here string | null is the type of city that can be a string or a null. But city here has not been initialised.

Have a look of the Advanced Types with detailed explanation URL: https://www.typescriptlang.org/docs/handbook/advanced-types.html

Hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM