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类型
}