- Angular UI Development with PrimeNG
- Sudheer Jonna Oleg Varaksin
- 224字
- 2021-07-15 17:32:55
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.
- R語(yǔ)言編程指南
- Python Network Programming Cookbook(Second Edition)
- Scientific Computing with Scala
- 大學(xué)計(jì)算機(jī)基礎(chǔ)實(shí)驗(yàn)指導(dǎo)
- Python爬蟲(chóng)、數(shù)據(jù)分析與可視化:工具詳解與案例實(shí)戰(zhàn)
- 快速入門與進(jìn)階:Creo 4·0全實(shí)例精講
- Java圖像處理:基于OpenCV與JVM
- AngularJS UI Development
- 你必須知道的.NET(第2版)
- Android開(kāi)發(fā)權(quán)威指南(第二版)
- 詩(shī)意的邊緣
- ASP.NET Core 2 High Performance(Second Edition)
- Cinder:Begin Creative Coding
- C# 10核心技術(shù)指南
- Python自動(dòng)化運(yùn)維:技術(shù)與最佳實(shí)踐