一步一步学习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类型
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值