TypeScript- basis -04- union type

Union type

Union type (Union Types) represents the value may be one of several types.

Simple example

let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
myFavoriteNumber = 7;
let myFavoriteNumber: string | number;
myFavoriteNumber = true;

// index.ts(2,1): error TS2322: Type 'boolean' is not assignable to type 'string | number'.
//   Type 'boolean' is not assignable to type 'number'.

Use the type of joint |to separate each type.

Here the let myFavoriteNumber: string | numbermeaning is to allow myFavoriteNumberthe type stringor number, but not other types.

Access union type of property or method

When TypeScript a joint uncertain variable of type in the end is what type, we can only access the properties or methods common to all types of this union type in :

function getLength(something: string | number): number {
    return something.length;
}

// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.
//   Property 'length' does not exist on type 'number'.

The above example, lengthis not stringand numberthe common attributes, so the error.

Access stringand numbertotal property is no problem:

function getString(something: string | number): string {
    return something.toString();
}

Union type of a variable is assigned at the time, it will infer a type according to the rules of type inference:

let myFavoriteNumber: string | number;
myFavoriteNumber = 'seven';
console.log(myFavoriteNumber.length); // 5
myFavoriteNumber = 7;
console.log(myFavoriteNumber.length); // 编译时报错

// index.ts(5,30): error TS2339: Property 'length' does not exist on type 'number'.

In the embodiment, the second row myFavoriteNumberis inferred become string, access its lengthproperties are not given.

The fourth line myFavoriteNumberis inferred became number, access to it lengthwhen the properties on the error.

Guess you like

Origin www.cnblogs.com/idspring/p/11784700.html