导航
let isDone: boolean = false;
let decLiteral: number = 6; // 十进制
let hexLiteral: number = 0xf00d; // 十六进制
let binaryLiteral: number = 0b1010; // 二级制
let octalLiteral: number = 0o744; // 八进制
let myName: string = "bob";
myName = "smith";
let sentence: string = `Hello, my name is ${ myName }.
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)
let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
let obj: {
num: string,
toString: () => void
} = {
num: '123',
toString: function() {}
}
// 在获取 obj. 时,就会有提示,说 obj 下边有 num、toString 两个属性
let obj: any = {
num: '123',
toString: function() {}
} // 改为 any 后,获取 obj. 时就没有提示了
let list: any[] = [1, true, "free"];
list[1] = 100;
let a;
a = '123';
a = 123;
function warnUser(): void {
console.log("This is my warning message");
}
TypeScript里,undefined
和 null
两者各自有自己的类型分别叫做 undefined
和 null
。 和 void
相似,它们的本身的类型用处不是很大:
// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;
默认情况下null
和undefined
是所有类型的子类型。 就是说你可以把 null
和 undefined
赋值给number类型的变量。
然而,当你指定了--strictNullChecks标记,null
和undefined
只能赋值给void和它们各自。 这能避免 很多常见的问题。 也许在某处你想传入一个 string
或 null
或 undefined
,你可以使用联合类型 string | null | undefined 。
never类型表示的是那些永不存在的值的类型。
// 返回never的函数必须存在无法达到的终点
function error(message: string): never {
throw new Error(message);
}
// 推断的返回值类型为never
function fail() {
return error("Something failed");
}
// 返回never的函数必须存在无法达到的终点
function infiniteLoop(): never {
while (true) {
}
}
object
表示非原始类型,也就是除number,string,boolean,symbol,null或undefined之外的类型。
写法方式
number[]
Array<number>
let arr: number[] = [1, 2, 3];
let arr2: (string | number)[] = [1, 2, '3'];
let list: Array<number> = [1, 2, 3];
interface List {
[index: number]: number
}
let list: List = [1, 2, 3];
// or 联合类型
interface List {
[index: number]: number | string
}
let list: List = [1, 2, 3, '4'];
interface Args {
[index: number]: any;
length: number;
}
function test() {
let args: Args = arguments;
}
// 函数声明
function add(x: number, y: number): number {
return x + y;
}
// 函数表达式
let myAdd = function(x: number, y: number): number { return x + y; };
// 完整函数类型
let myAdd: (x: number, y: number) => number =
function(x: number, y: number): number { return x + y; };
// 可选参数
function buildName(firstName: string, lastName?: string) {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
let result1 = buildName("Bob"); // works correctly now
let result2 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result3 = buildName("Bob", "Adams"); // ah, just right
// 默认参数(默认参数都放后边,不要放必填参数前边)
function buildName(firstName: string, lastName = "Smith") {
return firstName + " " + lastName;
}
let result1 = buildName("Bob"); // works correctly now, returns "Bob Smith"
let result2 = buildName("Bob", undefined); // still works, also returns "Bob Smith"
let result3 = buildName("Bob", "Adams", "Sr."); // error, too many parameters
let result4 = buildName("Bob", "Adams"); // ah, just right
// 剩余参数
function buildName(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");
let deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
cards: Array(52),
createCardPicker: function() {
return function() {
let pickedCard = Math.floor(Math.random() * 52);
let pickedSuit = Math.floor(pickedCard / 13);
return {suit: this.suits[pickedSuit], card: pickedCard % 13};
// 上边 return 对象中的 this 指向 window or undefined
}
}
}
let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();
alert("card: " + pickedCard.card + " of " + pickedCard.suit);
interface Card {
suit: string;
card: number;
}
interface Deck {
suits: string[];
cards: number[];
createCardPicker(this: Deck): () => Card;
}
let deck: Deck = {
suits: ["hearts", "spades", "clubs", "diamonds"],
cards: Array(52),
// NOTE: The function now explicitly specifies that its callee must be of type Deck
createCardPicker: function(this: Deck) {
return () => {
let pickedCard = Math.floor(Math.random() * 52);
let pickedSuit = Math.floor(pickedCard / 13);
return {suit: this.suits[pickedSuit], card: pickedCard % 13};
}
}
}
let cardPicker = deck.createCardPicker();
let pickedCard = cardPicker();
alert("card: " + pickedCard.card + " of " + pickedCard.suit);
constructor
中使用 super
,super
指向 父类.prototype.constructor
constructor
方法中使用 super
,super
指向 父类.prototype
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
// 父类 -- 基类
class Animal {
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
// 子类 -- 派生类
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
class Animal {
name: string;
constructor(theName: string) { this.name = theName; }
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Snake extends Animal {
constructor(name: string) {
super(name);
// 这里的 super 是 Animal.constructor ,也就是 Animal 的构造函数
// super(name) 返回的是子类 Snake 的实例, 即 super 内部的 this 指的 Snake 实例
// 这里的 super(name) 相当于
// Animal.prototype.constructor.call(this, name);
}
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
// 这里的 super 是 Animal.prototype
// super.move() 相当于 Animal.prototype.move()
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(distanceInMeters = 45) {
console.log("Galloping...");
super.move(distanceInMeters);
}
}
let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
class Animal {
public name: string;
public constructor(theName: string) { this.name = theName; }
public move(distanceInMeters: number) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Animal {
private name: string;
constructor(theName: string) { this.name = theName; }
}
new Animal("Cat").name; // 错误: 'name' 是私有的.
class Person {
protected name: string;
constructor(name: string) { this.name = name; }
}
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name)
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // 错误
可以使用 readonly 关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
在上面的例子中,我们必须在Octopus类里定义一个只读成员 name 和一个参数为 theName 的构造函数,并且立刻将 theName 的值赋给 name,这种情况经常会遇到。 参数属性可以方便地让我们在一个地方定义并初始化一个成员。 下面的例子是对之前 Octopus 类的修改版,使用了参数属性:
class Octopus {
readonly numberOfLegs: number = 8;
constructor(readonly name: string) {
}
}
注意看我们是如何舍弃了 theName,仅在构造函数里使用 readonly name: string 参数来创建和初始化 name 成员。 我们把声明和赋值合并至一处。
参数属性通过给构造函数参数前面添加一个访问限定符来声明。 使用 private 限定一个参数属性会声明并初始化一个私有成员;对于 public 和 protected 来说也是一样。
class Employee {
fullName: string;
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
class Grid {
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
let xDist = (point.x - Grid.origin.x);
let yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor (public scale: number) { }
}
let grid1 = new Grid(1.0); // 1x scale
let grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));
abstract class Animal {
abstract makeSound(): void; // 每个动物的叫法不一样,交给继承抽象类的类自己去实现
move(): void {
console.log('roaming the earch...');
}
}
class Snack extends Animal {
move(): void {
// 重写
}
makeSound(): void {} // 必须实现抽象类的抽象方法 makeSound
}
class Rhino extends Animal {
// move(): void {} // 可以不实现
makeSound(): void {} // 必须实现抽象类的抽象方法 makeSound
}
类定义会创建两个东西:类的实例类型和一个构造函数。 因为类可以创建出类型,所以你能够在允许使用接口的地方使用类。
class Point {
x: number;
y: number;
}
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};