转自 –> TypeScript入门-语法篇
自学笔记, 基于官方教程上的代码, 添加注释.
官方教程:
Handbook
// 1. Boolean,布尔
var isDone: boolean = false;
console.log(isDone);
// 2. Number,数值
var height: number = 6;
console.log(height);
// 3. String,字符串
var name: string = "bob"; // 可以双引号
var name1: string = 'tom'; // 也可以单引号
console.log(name);
console.log(name1);
// 4. Array,数组
var list:number[] = [1, 2, 3]; // 写法1
var list1:Array = [1, 2, 3]; // 写法2
console.log(list);
console.log(list1);
// 5. Enum,枚举
enum Color {Red, Green, Blue}
var c: Color = Color.Green;
console.log(c); // 获取值
console.log(Color[c]); // 获取键, string
console.log(Color["Green"]); // 获取值
// # enum的值默认从0开始递增, 也可以自己指定
enum Color1 {Red = 1, Green = 2, Blue = 4}
var c1: Color1 = Color1.Green;
console.log(c1); // 获取值
// 6. Any,任意对象
// # 需要小心使用, 会改变数据类型
var anylist:any[] = [1, true, "free"];
anylist[2] = 100;
console.log(anylist);
// 7. Void,方法不返回值
function warnUser(): void {
console.log("This is my warning message");
}
warnUser();
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
var myObj = {label: "only label"};
var myObj1 = {size: 10, label: "Size 10 Object"};
// # 接口是鸭子类型, 只要是有label的对象都可以传进去
printLabel(myObj);
printLabel(myObj1);
interface SquareConfig {
color?: string; // 用?来表示可选属性
width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
var newSquare = {color: "white", area: 100}; // 默认值
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
var mySquare = createSquare({color: "black"});
var mySquare1 = createSquare({width: 20});
console.log(mySquare);
console.log(mySquare1);
interface SearchFunc {
(source: string, subString: string): boolean; // 表示一个接受2个string参数, 返回bool的函数
}
var mySearch: SearchFunc;
mySearch = function(source: string, subString: string): boolean {
var result = source.search(subString);
if (result == -1) {
return false;
}
else {
return true;
}
};
var result: boolean = mySearch("test", "te");
console.log(result);
interface StringArray {
[index: number]: string; // 表示string数组
}
var myArray: StringArray;
myArray = ["Bob", "Fred"];
console.log(myArray["0"]);
console.log(myArray["1"]);
interface ClockStatic {
new (hour: number, minute: number);
}
// # 这里会报错. 因为只有实例部分才检查, 而构造函数是静态部分
//class Clock implements ClockStatic {
// currentTime: Date;
// constructor(h: number, m: number) { }
//}
class Clock {
currentTime: Date;
constructor(h: number, m: number) { }
}
// # 这里需要注意
// # 我们直接使用class,这样就会检查签名
var cs: ClockStatic = Clock;
var newClock: ClockStatic = new cs(7, 30);
console.log(newClock);
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke { // 使用extends继承接口
sideLength: number;
}
var square = {};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
var c: Counter;
c(10); // c可以当函数
c.reset(); // c也可以当对象
c.interval = 5.0; // c的属性
class Greeter {
greeting: string; // 属性
constructor(message: string) { // 构造函数
this.greeting = message;
}
greet(): string { // 方法
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("world");
var result = greeter.greet();
console.log(result);
class Animal {
name:string;
constructor(theName: string) { this.name = theName; }
move(meters: number = 0) {
console.log(this.name + " moved " + meters + "m.");
}
}
class Snake extends Animal { // 使用extends关键字来继承
constructor(name: string) { super(name); }
move(meters = 5) {
console.log("Slithering...");
super.move(meters);
}
}
class Horse extends Animal {
constructor(name: string) { super(name); }
move(meters = 45) {
console.log("Galloping...");
super.move(meters);
}
}
var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");
sam.move();
tom.move(34);
class Animal {
private name:string; // 除非指定为private, 否则默认是public
constructor(theName: string) { this.name = theName; }
move(meters: number) {
alert(this.name + " moved " + meters + "m.");
}
}
class Animal {
private name:string;
constructor(theName: string) { this.name = theName; }
}
class Rhino extends Animal {
constructor() { super("Rhino"); }
}
class Employee {
private name:string;
constructor(theName: string) { this.name = theName; }
}
var animal = new Animal("Goat");
var rhino = new Rhino();
var employee = new Employee("Bob");
animal = rhino;
//animal = employee; // # 这里会报错. 虽然Animal和Employee属性名一致, 但是私有属性来源不一致
class A {
public name: string;
echo() {}
}
class B {
public name: string;
echo() {}
}
var a = new A();
var b = new B();
a = b; // 公有属性则没有关系
class Animal {
constructor(private name: string) { } // 可以在构造方法用private直接指定属性,省去一步
move(meters: number) {
console.log(this.name + " moved " + meters + "m.");
}
}
var dog = new Animal("dog");
dog.move(3);
var passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string { // 读属性. # 需要编译版本为ECMAScript 5
return this._fullName;
}
set fullName(newName: string) { // 写属性. # 需要编译版本为ECMAScript 5
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
var employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
class Grid {
static origin = {x: 0, y: 0}; // 用static定义静态属性
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
var xDist = (point.x - Grid.origin.x);
var yDist = (point.y - Grid.origin.y);
return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
}
constructor (public scale: number) { }
}
var grid1 = new Grid(1.0); // 1x scale
var grid2 = new Grid(5.0); // 5x scale
console.log(grid1.calculateDistanceFromOrigin({x: 10, y: 10}));
console.log(grid2.calculateDistanceFromOrigin({x: 10, y: 10}));