官术网_书友最值得收藏!

Union types and type aliases

A union type describes a value that can be one of many types. The vertical bar | is used as separator for each type the value can have. For instance, number | string is the type of a value that can be a number or string. For such values, we can only access members that are common to all types in the union. The following code works because the length property exists on both strings and arrays:

var value: string | string[] = 'some';
let length = value.length;

The next code snippet gives an error because the model property does not exist on the Bike type:

interface Bike {
gears: number;
}

interface Car {
gears: number;
model: string;
}

var transport: Bike | Car = {gears: 1};
transport.model = "Audi"; // compiler error

Type alias is used as alternative name for the existing type or combination of types. It doesn't create a new type. A type alias begins with the type keyword.

type PrimitiveArray = Array<string|number|boolean>;
type Callback = () => number;
type PrimitiveArrayOrCallback = PrimitiveArray | Callback;

Type aliases can be used for better code readability, for example, in the function parameter list.

function doSomething(n: PrimitiveArrayOrCallback): number {
...
}

Type aliases can also be generic and make tricky types, which can not be made with interfaces.

主站蜘蛛池模板: 贵南县| 新源县| 尤溪县| 洮南市| 磐安县| 香港| 元氏县| 永定县| 江华| 和硕县| 垫江县| 辉南县| 比如县| 宕昌县| 祥云县| 阿城市| 滕州市| 孟州市| 江达县| 错那县| 札达县| 镇沅| 司法| 股票| 梨树县| 安图县| 友谊县| 井冈山市| 德保县| 宝丰县| 鹿邑县| 石狮市| 成都市| 广昌县| 巨野县| 巴林左旗| 杭锦后旗| 广西| 全州县| 大英县| 马鞍山市|