let sjfName: string = "sunjianfeng";
// array 可以包含不同类型的数据ß
let arr: Array<number> = [1, 3, 4];
enum Color {
Red = 1,
Green,
Blue,
}
let sjfColor: Color = Color.Blue;
// 类型诊断不是类型转换,不进行数据的检查和解构,只在编译阶段起作用
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// 或者
let strLength2: number = (someValue as string).length;
// var 声明的变量是函数作用域,只要在函数内声明就会在函数内的任何地方访问到
// 使用let 替代var
// const 与let 有相同的作用域,只是一旦赋值就不能改变
// 解构数组
let input = [1, 2];
let [first, second] = input;
// 对象解构
let o = { a: "foo", b: 12 };
//let {a,b} = o;
// 支持... 但是必须是对象中的属性名。... 后的参数名可以任意
let { a, ...passthrough } = o;
// 属性重命名
let { a: newname1, b: newName2 } = o;
// 默认值
function f({ a, b = 0 } = { a: "", b: 0 }) {
}
//展开
let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
let search = { ...defaults, food: "rich" };
// 对象的展开会 丢失方法&& 只能展开自身可枚举的属性
// 可选属性
interface SquareConfig {
color?: string;
readonly x: number;
}
//接口函数
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearchF: SearchFunc;
mySearchF = function (s: string, s2: string) {
return true;
}
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
interface ClockInterface {
currentTime: Date;
}
class TenClock implements ClockInterface {
currentTime: Date;
constructor(h: number, m: number) {
}
}
//一个接口可以继承多个接口 interface Shape extends XX, XC,XS { }
// 一个对象可以同时作为函数和对象使用
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = <Counter>function (start: number) {
};
counter.interval = 123;
counter.reset = function () {
};
return counter;
}
let ccounter = getCounter();
ccounter(10);
ccounter.interval = 5.0;
// 访问控制
// 默认是public
// 静态成员 static
// 抽象类和抽象方法
abstract class Department {
name: string;
constructor(name: string) {
this.name = name;
}
printName(): void {
console.log("Department name: " + this.name);
}
abstract printMethod():void;
}
/*
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter: Greeter;
greeter = new Greeter("world");
console.log(greeter.greet());
// 转换为js
let Greeter = (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
let greeter;
greeter = new Greeter("world");
console.log(greeter.greet());
*/