一步一步學習TypeScript(12.Union Types_聯合類型)

union types (聯合類型)

考慮如下情況,如果一個變量在聲明時可以有幾個不同的類型,需要跟據運行時所傳入的參數不同而改變相應類型,這種情況在typescript裏應該怎麼寫.

先看一下怎麼使用union type

var command:string|string[];

command = 'strat';  //正確, string

command = ['strat', 'stop'];  //正確, string[]

command = 123;  //錯誤, 沒有聲明number類型

考慮之間的情況我們可以定義一個函數:

function run(command: string|string[]){
    if(typeof command === 'string'){ //command會被當成string類型
        command.substr(0);
    }else{ //command 會被當成string[]類型
        command.join();
        command.substr(0); //錯誤, 方法substr在string[]中不存在
    }
}

run('start');

run(['start','stop']);

typeof 或 instanceof

可以使用typeof判斷變量類型一般爲number,boolean,string,function,object,undefined這幾種之一
如使用typeof來推斷一個變量類型:

var x: any = /* ... */;
if(typeof x === 'string') {
   /* 這個方法塊內x會被當作string進行處理 */
}

使用instanceof來推斷一個類或接口的類型

class Pig{ eat(){ } }

class People{ say(){ } }

var animal: Pig|People = new Pig();

if(animal instanceof Pig){
    animal.eat();
}else if(animal instanceof People){
    animal.say();
    animal.eat(); //錯誤, eat方法在People中不存在
}

Better Type Inference (智能類型推斷)

// other跟據現有值,會被當作一個 Array<string|number>
var other = ['love',2]; 
other [0] = 888; // 正確
other [0] = false; // 錯誤, 不是一個string或number

Type Aliases (類型別名)

當聯合類型過長時,爲個美觀可以使用type爲類型定義一個別名:

type StringNumberOrBoolean = string | number | boolean;
type PrimitiveArray = Array<string|number|boolean>;
type MyNumber = number;
type Callback = () => void;
type CallbackWithString = (string) => void;

//使用上面的別名
function work(x: StringNumberOrBoolean){
}

function usingCallback(f: CallbackWithString){
    f("This is a string");
}

User defined type guards (自定義類型推斷)

interface Animal {name: string; }
interface Cat extends Animal { meow(); }

//使用 a is Cat, 當條件爲真時, 將會把 a 轉爲Cat類型
function isCat(a: Animal): a is Cat {
  return a.name === 'kitty';
}

var x: Animal;

if(isCat(x)) {
  x.meow(); // OK, 在這個範圍內x是Cat類型
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章