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 | number
meaning is to allow myFavoriteNumber
the type string
or 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, length
is not string
and number
the common attributes, so the error.
Access string
and number
total 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 myFavoriteNumber
is inferred become string
, access its length
properties are not given.
The fourth line myFavoriteNumber
is inferred became number
, access to it length
when the properties on the error.
- This article refers to xcatliu