新聞中心
交叉類型(Intersection Types)
交叉類型是將多個類型合并為一個類型。 這讓我們可以把現(xiàn)有的多種類型疊加到一起成為一種類型,它包含了所需的所有類型的特性。 例如, Person & Serializable & Loggable同時是Person和Serializable和Loggable。 就是說這個類型的對象同時擁有了這三種類型的成員。

創(chuàng)新互聯(lián)建站是一家企業(yè)級云計算解決方案提供商,超15年IDC數(shù)據(jù)中心運營經(jīng)驗。主營GPU顯卡服務器,站群服務器,成都機柜租用,海外高防服務器,大帶寬服務器,動態(tài)撥號VPS,海外云手機,海外云服務器,海外服務器租用托管等。
我們大多是在混入(mixins)或其它不適合典型面向對象模型的地方看到交叉類型的使用。 (在JavaScript里發(fā)生這種情況的場合很多!) 下面是如何創(chuàng)建混入的一個簡單例子:
function extend(first: T, second: U): T & U {
let result = {};
for (let id in first) {
(result)[id] = (first)[id];
}
for (let id in second) {
if (!result.hasOwnProperty(id)) {
(result)[id] = (second)[id];
}
}
return result;
}
class Person {
constructor(public name: string) { }
}
interface Loggable {
log(): void;
}
class ConsoleLogger implements Loggable {
log() {
// ...
}
}
var jim = extend(new Person("Jim"), new ConsoleLogger());
var n = jim.name;
jim.log();
聯(lián)合類型
聯(lián)合類型與交叉類型很有關聯(lián),但是使用上卻完全不同。 偶爾你會遇到這種情況,一個代碼庫希望傳入 number或string類型的參數(shù)。 例如下面的函數(shù):
/**
* Takes a string and adds "padding" to the left.
* If 'padding' is a string, then 'padding' is appended to the left side.
* If 'padding' is a number, then that number of spaces is added to the left side.
*/
function padLeft(value: string, padding: any) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
padLeft("Hello world", 4); // returns " Hello world"
padLeft存在一個問題,padding參數(shù)的類型指定成了any。 這就是說我們可以傳入一個既不是 number也不是string類型的參數(shù),但是TypeScript卻不報錯。
let indentedString = padLeft("Hello world", true); // 編譯階段通過,運行時報錯
在傳統(tǒng)的面向對象語言里,我們可能會將這兩種類型抽象成有層級的類型。 這么做顯然是非常清晰的,但同時也存在了過度設計。 padLeft原始版本的好處之一是允許我們傳入原始類型。 這樣做的話使用起來既簡單又方便。 如果我們就是想使用已經(jīng)存在的函數(shù)的話,這種新的方式就不適用了。
代替any, 我們可以使用聯(lián)合類型做為padding的參數(shù):
/**
* Takes a string and adds "padding" to the left.
* If 'padding' is a string, then 'padding' is appended to the left side.
* If 'padding' is a number, then that number of spaces is added to the left side.
*/
function padLeft(value: string, padding: string | number) {
// ...
}
let indentedString = padLeft("Hello world", true); // errors during compilation
聯(lián)合類型表示一個值可以是幾種類型之一。 我們用豎線( |)分隔每個類型,所以number | string | boolean表示一個值可以是number,string,或boolean。
如果一個值是聯(lián)合類型,我們只能訪問此聯(lián)合類型的所有類型里共有的成員。
interface Bird {
fly();
layEggs();
}
interface Fish {
swim();
layEggs();
}
function getSmallPet(): Fish | Bird {
// ...
}
let pet = getSmallPet();
pet.layEggs(); // okay
pet.swim(); // errors
這里的聯(lián)合類型可能有點復雜,但是你很容易就習慣了。 如果一個值的類型是 A | B,我們能夠確定的是它包含了A和B中共有的成員。 這個例子里, Bird具有一個fly成員。 我們不能確定一個 Bird | Fish類型的變量是否有fly方法。 如果變量在運行時是 Fish類型,那么調用pet.fly()就出錯了。
類型保護與區(qū)分類型
聯(lián)合類型非常適合這樣的情形,可接收的值有不同的類型。 當我們想明確地知道是否拿到 Fish時會怎么做? JavaScript里常用來區(qū)分2個可能值的方法是檢查它們是否存在。 像之前提到的,我們只能訪問聯(lián)合類型的所有類型中共有的成員。
let pet = getSmallPet();
// 每一個成員訪問都會報錯
if (pet.swim) {
pet.swim();
}
else if (pet.fly) {
pet.fly();
}
為了讓這段代碼工作,我們要使用類型斷言:
let pet = getSmallPet();
if ((pet).swim) {
(pet).swim();
}
else {
(pet).fly();
}
用戶自定義的類型保護
可以注意到我們使用了多次類型斷言。 如果我們只要檢查過一次類型,就能夠在后面的每個分支里清楚 pet的類型的話就好了。
TypeScript里的類型保護機制讓它成為了現(xiàn)實。 類型保護就是一些表達式,它們會在運行時檢查以確保在某個作用域里的類型。 要定義一個類型保護,我們只要簡單地定義一個函數(shù),它的返回值是一個 類型斷言:
function isFish(pet: Fish | Bird): pet is Fish {
return (pet).swim !== undefined;
}
在這個例子里,pet is Fish就是類型謂詞。 謂詞是 parameterName is Type這種形式,parameterName必須是來自于當前函數(shù)簽名里的一個參數(shù)名。
每當使用一些變量調用isFish時,TypeScript會將變量縮減為那個具體的類型,只要這個類型與變量的原始類型是兼容的。
// 'swim' 和 'fly' 調用都沒有問題了
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
}
注意TypeScript不僅知道在if分支里pet是Fish類型; 它還清楚在 else分支里,一定不是Fish類型,一定是Bird類型。
typeof類型保護
現(xiàn)在我們回過頭來看看怎么使用聯(lián)合類型書寫padLeft代碼。 我們可以像下面這樣利用類型斷言來寫:
function isNumber(x: any): x is number {
return typeof x === "number";
}
function isString(x: any): x is string {
return typeof x === "string";
}
function padLeft(value: string, padding: string | number) {
if (isNumber(padding)) {
return Array(padding + 1).join(" ") + value;
}
if (isString(padding)) {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
然而,必須要定義一個函數(shù)來判斷類型是否是原始類型,這太痛苦了。 幸運的是,現(xiàn)在我們不必將 typeof x === "number"抽象成一個函數(shù),因為TypeScript可以將它識別為一個類型保護。 也就是說我們可以直接在代碼里檢查類型了。
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
這些*typeof類型保護*只有兩種形式能被識別:typeof v === "typename"和typeof v !== "typename","typename"必須是"number","string","boolean"或"symbol"。 但是TypeScript并不會阻止你與其它字符串比較,語言不會把那些表達式識別為類型保護。
instanceof類型保護
如果你已經(jīng)閱讀了typeof類型保護并且對JavaScript里的instanceof操作符熟悉的話,你可能已經(jīng)猜到了這節(jié)要講的內容。
instanceof類型保護是通過構造函數(shù)來細化類型的一種方式。 比如,我們借鑒一下之前字符串填充的例子:
interface Padder {
getPaddingString(): string
}
class SpaceRepeatingPadder implements Padder {
constructor(private numSpaces: number) { }
getPaddingString() {
return Array(this.numSpaces + 1).join(" ");
}
}
class StringPadder implements Padder {
constructor(private value: string) { }
getPaddingString() {
return this.value;
}
}
function getRandomPadder() {
return Math.random() < 0.5 ?
new SpaceRepeatingPadder(4) :
new StringPadder(" ");
}
// 類型為SpaceRepeatingPadder | StringPadder
let padder: Padder = getRandomPadder();
if (padder instanceof SpaceRepeatingPadder) {
padder; // 類型細化為'SpaceRepeatingPadder'
}
if (padder instanceof StringPadder) {
padder; // 類型細化為'StringPadder'
}
instanceof的右側要求是一個構造函數(shù),TypeScript將細化為:
- 此構造函數(shù)的
prototype屬性的類型,如果它的類型不為any的話 - 構造簽名所返回的類型的聯(lián)合
以此順序。
類型別名
類型別名會給一個類型起個新名字。 類型別名有時和接口很像,但是可以作用于原始值,聯(lián)合類型,元組以及其它任何你需要手寫的類型。
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
if (typeof n === 'string') {
return n;
}
else {
return n();
}
}
起別名不會新建一個類型 - 它創(chuàng)建了一個新名字來引用那個類型。 給原始類型起別名通常沒什么用,盡管可以做為文檔的一種形式使用。
同接口一樣,類型別名也可以是泛型 - 我們可以添加類型參數(shù)并且在別名聲明的右側傳入:
type Container = { value: T };
我們也可以使用類型別名來在屬性里引用自己:
type Tree = {
value: T;
left: Tree;
right: Tree;
}
然而,類型別名不能夠出現(xiàn)在聲名語句的右側:
type LinkedList = T & { next: LinkedList };
interface Person {
name: string;
}
var people: LinkedList;
var s = people.name;
var s = people.next.name;
var s = people.next.next.name;
var s = people.next.next.next.name;
然而,類型別名不能出現(xiàn)在聲明右側的任何地方。
type Yikes = Array; // error
接口 vs. 類型別名
像我們提到的,類型別名可以像接口一樣;然而,仍有一些細微差別。
其一,接口創(chuàng)建了一個新的名字,可以在其它任何地方使用。 類型別名并不創(chuàng)建新名字—比如,錯誤信息就不會使用別名。 在下面的示例代碼里,在編譯器中將鼠標懸停在 interfaced上,顯示它返回的是Interface,但懸停在aliased上時,顯示的卻是對象字面量類型。
type Alias = { num: number }
interface Interface {
num: number;
}
declare function aliased(arg: Alias): Alias;
declare function interfaced(arg: Interface): Interface;
另一個重要區(qū)別是類型別名不能被extends和implements(自己也不能extends和implements其它類型)。 因為 軟件中的對象應該對于擴展是開放的,但是對于修改是封閉的,你應該盡量去使用接口代替類型別名。
另一方面,如果你無法通過接口來描述一個類型并且需要使用聯(lián)合類型或元組類型,這時通常會使用類型別名。
字符串字面量類型
字符串字面量類型允許你指定字符串必須的固定值。 在實際應用中,字符串字面量類型可以與聯(lián)合類型,類型保護和類型別名很好的配合。 通過結合使用這些特性,你可以實現(xiàn)類似枚舉類型的字符串。
type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
animate(dx: number, dy: number, easing: Easing) {
if (easing === "ease-in") {
// ...
}
else if (easing === "ease-out") {
}
else if (easing === "ease-in-out") {
}
else {
// error! should not pass null or undefined.
}
}
}
let button = new UIElement();
button.animate(0, 0, "ease-in");
button.animate(0, 0, "uneasy"); // error: "uneasy" is not allowed here
你只能從三種允許的字符中選擇其一來做為參數(shù)傳遞,傳入其它值則會產(chǎn)生錯誤。
Argument of type '"uneasy"' is not assignable to parameter of type '"ease-in" | "ease-out" | "ease-in-out"'
字符串字面量類型還可以用于區(qū)分函數(shù)重載:
function createElement(tagName: "img"): HTMLImageElement;
function createElement(tagName: "input"): HTMLInputElement;
// ... more overloads ...
function createElement(tagName: string): Element {
// ... code goes here ...
}
可辨識聯(lián)合(Discriminated Unions)
你可以合并字符串字面量類型,聯(lián)合類型,類型保護和類型別名來創(chuàng)建一個叫做可辨識聯(lián)合的高級模式,它也稱做標簽聯(lián)合或代數(shù)數(shù)據(jù)類型。 可辨識聯(lián)合在函數(shù)式編程很有用處。 一些語言會自動地為你辨識聯(lián)合;而TypeScript則基于已有的JavaScript模式。 它具有4個要素:
- 具有普通的字符串字面量屬性—可辨識的特征。
- 一個類型別名包含了那些類型的聯(lián)合—聯(lián)合。
- 此屬性上的類型保護。
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
interface Circle {
kind: "circle";
radius: number;
}
首先我們聲明了將要聯(lián)合的接口。 每個接口都有 kind屬性但有不同的字符器字面量類型。 kind屬性稱做可辨識的特征或標簽。 其它的屬性則特定于各個接口。 注意,目前各個接口間是沒有聯(lián)系的。 下面我們把它們聯(lián)合到一起:
type Shape = Square | Rectangle | Circle;
現(xiàn)在我們使用可辨識聯(lián)合:
function area(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
}
}
完整性檢查
當沒有涵蓋所有可辨識聯(lián)合的變化時,我們想讓編譯器可以通知我們。 比如,如果我們添加了 Triangle到Shape,我們同時還需要更新area:
type Shape = Square | Rectangle | Circle | Triangle;
function area(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
}
// should error here - we didn't handle case "triangle"
}
有兩種方式可以實現(xiàn)。 首先是啟用 --strictNullChecks并且指定一個返回值類型:
function area(s: Shape): number { // error: returns number | undefined
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
}
}
因為switch沒有包涵所有情況,所以TypeScript認為這個函數(shù)有時候會返回undefined。 如果你明確地指定了返回值類型為 number,那么你會看到一個錯誤,因為實際上返回值的類型為number | undefined。 然而,這種方法存在些微妙之處且 --strictNullChecks對舊代碼支持不好。
第二種方法使用never類型,編譯器用它來進行完整性檢查:
function assertNever(x: never): never {
throw new Error("Unexpected object: " + x);
}
function area(s: Shape) {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.height * s.width;
case "circle": return Math.PI * s.radius ** 2;
default: return assertNever(s); // error here if there are missing cases
}
}
這里,assertNever檢查s是否為never類型—即為除去所有可能情況后剩下的類型。 如果你忘記了某個case,那么 s將具有一個趕寫的類型,因此你會得到一個錯誤。 這種方式需要你定義一個額外的函數(shù)。
多態(tài)的this類型
多態(tài)的this類型表示的是某個包含類或接口的子類型。 這被稱做 F-bounded多態(tài)性。 它能很容易的表現(xiàn)連貫接口間的繼承,比如。 在計算器的例子里,在每個操作之后都返回 this類型:
class BasicCalculator {
public constructor(protected value: number = 0) { }
public currentValue(): number {
return this.value;
}
public add(operand: number): this {
this.value += operand;
return this;
}
public multiply(operand: number): this {
this.value *= operand;
return this;
}
// ... other operations go here ...
}
let v = new BasicCalculator(2)
.multiply(5)
.add(1)
.currentValue();
由于這個類使用了this類型,你可以繼承它,新的類可以直接使用之前的方法,不需要做任何的改變。
class ScientificCalculator extends BasicCalculator {
public constructor(value = 0) {
super(value);
}
public sin() {
this.value = Math.sin(this.value);
return this;
}
// ... other operations go here ...
}
let v = new ScientificCalculator(2)
.multiply(5)
.sin()
.add(1)
.currentValue();
如果沒有this類型,ScientificCalculator就不能夠在繼承BasicCalculator的同時還保持接口的連貫性。 multiply將會返回BasicCalculator,它并沒有sin方法。 然而,使用 this類型,multiply會返回this,在這里就是ScientificCalculator。
文章標題:創(chuàng)新互聯(lián)TypeScript教程:TypeScript高級類型
瀏覽路徑:http://m.5511xx.com/article/ccsgsgd.html


咨詢
建站咨詢
