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

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.

主站蜘蛛池模板: 当阳市| 高密市| 栾城县| 娄烦县| 平乐县| 睢宁县| 章丘市| 敦煌市| 盖州市| 增城市| 马公市| 义乌市| 佛冈县| 罗江县| 蒲城县| 阿瓦提县| 乐陵市| 丰原市| 时尚| 闻喜县| 苏尼特左旗| 锦州市| 东海县| 芷江| 治多县| 宁陕县| 延川县| 南雄市| 泰来县| 鄂托克旗| 马关县| 大理市| 岳西县| 无锡市| 山阳县| 竹溪县| 惠东县| 鸡东县| 汶川县| 卢湾区| 叙永县|