- 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.
- Go語言高效編程:原理、可觀測性與優化
- JavaScript+jQuery網頁特效設計任務驅動教程(第2版)
- JavaScript語言精髓與編程實踐(第3版)
- JIRA 7 Administration Cookbook(Second Edition)
- 軟件測試工程師面試秘籍
- R語言編程指南
- Selenium Testing Tools Cookbook(Second Edition)
- Yii Project Blueprints
- PHP從入門到精通(第4版)(軟件開發視頻大講堂)
- Vue.js應用測試
- ASP.NET開發寶典
- 零基礎入門學習C語言:帶你學C帶你飛
- Mastering High Performance with Kotlin
- Java性能權威指南
- 嵌入式網絡編程