function formatCommandline(c: string|string[]) {
if(typeof c === 'string') {
return c.trim();
} else {
return c.join(' ');
}
}
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
console.log(x); // meant to write 'y' here
/* later in the same block */
var x = 'hello';
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
}
const halfPi = Math.PI / 2;
halfPi = 2; // Error, can't assign to a `const`
var name = "TypeScript";
var greeting = `Hello, ${name}! Your name has ${name.length} characters`;
var name = "TypeScript!";
var greeting = "Hello, " + name + "! Your name has " + name.length + " characters";
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
var x: string|HTMLElement = /* ... */;
if(typeof x === 'string') {
// x is string here, as shown above
} else {
// x is HTMLElement here
console.log(x.innerHTML);
}
class Dog { woof() { } }
class Cat { meow() { } }
var pet: Dog|Cat = /* ... */;
if(pet instanceof Dog) {
pet.woof(); // OK
} else {
pet.woof(); // Error
}
type PrimitiveArray = Array<string|number|boolean>;
type MyNumber = number;
type NgScope = ng.IScope;
type Callback = () => void;
const enum Suit { Clubs, Diamonds, Hearts, Spades }
var d = Suit.Diamonds;
var d = 1;
enum MyFlags {
None = 0,
Neat = 1,
Cool = 2,
Awesome = 4,
Best = Neat | Cool | Awesome
}
var b = MyFlags.Best; // emits var b = 7;
//// [amdModule.ts]
///<amd-module name='NamedModule'/>
export class C {
}
//// [amdModule.js]
define("NamedModule", ["require", "exports"], function (require, exports) {
var C = (function () {
function C() {
}
return C;
})();
exports.C = C;
});