function equal<T>(lhs: T, rhs: T): boolean {
return lhs === rhs;
}
// 之前没有错误
// 现在会报错:在string和number之前没有最佳的基本类型
var e = equal(42, 'hello');
通过联合类型,你可以指定你想要的行为,在函数定义时或在调用的时候:
// 'choose' function where types must match
function choose1<T>(a: T, b: T): T { return Math.random() > 0.5 ? a : b }
var a = choose1('hello', 42); // Error
var b = choose1<string|number>('hello', 42); // OK
// 'choose' function where types need not match
function choose2<T, U>(a: T, b: U): T|U { return Math.random() > 0.5 ? a : b }
var c = choose2('bar', 'foo'); // OK, c: string
var d = choose2('hello', 42); // OK, d: string|number
更好的类型推断
当一个集合里有多种类型的值时,联合类型会为数组或其它地方提供更好的类型推断:
var x = [1, 'hello']; // x: Array<string|number>
x[0] = 'world'; // OK
x[0] = false; // Error, boolean is not string or number
if(foo) {
console.log(x); // Error, cannot refer to x before its declaration
let x = 'hello';
} else {
console.log(x); // Error, x is not declared in this block
}
var x: any = /* ... */;
if(typeof x === 'string') {
console.log(x.subtr(1)); // Error, 'subtr' does not exist on 'string'
}
// x is still any here
x.unknown(); // OK
结合联合类型使用typeof和else:
var x: string|HTMLElement = /* ... */;
if(typeof x === 'string') {
// x is string here, as shown above
} else {
// x is HTMLElement here
console.log(x.innerHTML);
}
结合类和联合类型使用instanceof:
class Dog { woof() { } }
class Cat { meow() { } }
var pet: Dog|Cat = /* ... */;
if(pet instanceof Dog) {
pet.woof(); // OK
} else {
pet.woof(); // Error
}
类型别名
你现在可以使用type关键字来为类型定义一个“别名”:
type PrimitiveArray = Array<string|number|boolean>;
type MyNumber = number;
type NgScope = ng.IScope;
type Callback = () => void;