基础类型
1、布尔值: let isDone: boolean = false;
2、数字: let decLiteral: number= 6; //十进制let decLiteral: number = 0xf00d; //十六进制
3、字符串: let name: string = "bob";
4、数组(两种定义方式): let list: number[=[1,2, 3]; let list: Array=[1,2, 3];
5、元组(表示一个已知元素数量和类型的数组): let x:[string, number]; x = ['hello', 10];当访问一个越界的元素,会使用联合类型替代:x[3]可以赋值string, number两种类型
6、枚举(为一组数值赋予友好的名字):
enum Color {Red= 1, Green = 2, Blue = 4}; console.log(Color[1],Color.Red) // Red 17、任意值: let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; let list: any[] = [1,true, "free"];
8、空值(当函数没有返回值时,返回为void; void类型只能赋值undefined和null):
function warnUser():void {alert("This is my warning message");}
let unusable: void = undefined;9、Null 和Undefined: let u: undefined = undefined; let n: null = null;
变量声明
1、 var与let区别
var为函数作用域,函数,模块,命名空间或全局作用域内部任何位置被访问,且在同一作用域内重复声明并不会报错; let为块级作用域,在块级外不能访问,不能重复声明,且不能声明前调用,声明前为暂时性死区。
for (vari= 0; i< matrix.length; i++) {
var currentRow = matrix[i];
for (var i= 0; i< currentRow.length; i++) {
//用var因为i洞一作用域声明,会造成混乱;用let因为for循环单独一个作用域,能得到正确的结果
for (vari= 0;i< 10;i++) {
setTimeout(function() { console.log(i);}, 100 *i);
}
//用var打印结果都为10;用let会打印0-10不同的数字2、解构(...语法创建剩余变量)
数组:
let input = [1, 2];let [first, second] = input;
console.log(first); // outputs 1
console.log(second); // outputs 2
let [first, ..rest] = [1, 2, 3, 4];console.log(first); //outputs 1
console.log(rest); // outputs [2, 3, 4]
对象:
let o={a: "foo", b: 12, c: "bar"};let{a,b}= o;
let { a, ..passthrough } = o;
let total =passthrough.b + passthrough.c.length;3、展开
数组:
let first = [1, 2]; let second = [3, 4]; let bothPlus = [0, ..frst,,..econd, 5];
对象:
let defaults = { food: "spicy", price: "$$", ambiance: "noisy" };
let search = { ..defaults,food: "rich" };接口(INTERFACE)
接口是对值所具有的结构进行类型检查。
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);可选属性:接口里的属性不全是必须的。
interface SquareConfig {
color?: string;
width?: number;
}只读属性:只能在对象刚刚创建的时候修改其值。
interface Point {
readonly X: number;
readonly y: number;,
}函数类型:
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}可索引的类型:
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = T"Bob", "Fred"];
let myStr: string = myArray[0];类类型:强制- -个类去符合某种契约
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date;
constructor(h: number, m: number) { }
}继承接口:
interface Shape {
color: string;
}
interface Square extends Shape {
sideL ength: number;
}
let square = {};
square.color= "blue";
square.sideLength = 10;类
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");继承:
class Animal {
move(distancelnMeters: number = 0) {
console.log(`Animal moved ${distancelnMeters}m.`);
}
}
class Dog extends Animal {
bark() {
console.log("Woof! Woof!");
}
}
const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();公共,私有与受保护的修饰符:
默认为公共public:
class Animal {
public name: string;
public constructor(theName: string) {
=theName;
}
public move(distancelnMeters: number) {
console.log(`${} moved${distancelnMeters}m.`);
}
}私有private:不能在声明它的类的外部访问
class Animal {
private name: string;
constructor(theName: string) {
= theName;
}
new Animal("Cat").name; //错误: 'name'是私有的.TypeScript使用的是结构性类型系统;赋值必须得类
型匹配兼容,比较带有private或protected成员的类
型,如果不是同一处声明private或protected类型,
则无法匹配;
class Animal {
private name: string;
constructor(theName: string) {
=theName;
}
}
class Rhino extends Animal{
constructor() { super("Rhino"); }
}
class Employee {
private name: string;
constructor(theName: string) {
= theName;
}
}
let animal = new Animal("Goat'");
let rhino = new Rhino();
let employee = new Employee("Bob");
animal = rhino;
animal = employee; //错误: Animal与Employee 不兼容.受保护protected:
protected修饰符与private修饰符的行为很相似,但
有一点不同,protected成员在派生类中仍然可以访
问。
class Person {
protected name: string;
constructor(name: string) { = 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 ${} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch();
console.log(); //错误构造函数也可以被标记成protected。这意味着这个
类不能在包含它的类外被实例化,但是能被继承
存取器: TypeScript支 持通过getters/setters来截不
对对象成员的访问。
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._fulName = newName;
} else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee. fullName);
}静态属性:属性存在于类本身上面而不是类的实例
上;通过类名访问而不是实例
抽象类:抽象方法的语法与接口方法相似。两者都
是定义方法签名但不包含方法体。然而,抽象方法
必须包含abstract关键字并且可以包含访问修饰符。
abstract class Department {
constructor(public name: string) {}
printName(): void {
console.log('Department name:' + );
}
abstract printMeeting(): void; //必须在派生类中实现
}
class AccountingDepartment extends Department {
constructor() {
super('Accounting and Auditing'); //在派生类的构造函数中必须调用super()
}
printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports(): void {
console.log('Generating accounting repors..');
}
}
let department: Department; //允许创建一个 对抽象类型的引用.
department = new Department(); //错误:不能创建一个抽象类的实例
department = new AccountingDepartment(); //允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
department.generateReports(); //错误:方法在声明.的抽象类中不存在函数
可选参数和默认参数: buildName(firstName: string,lastName?: string) 与buildName(firstName: string,lastName = "Smith")等价
剩余参数(.... : function buildName(firstName:string, ..estOfName: string[)
This:箭头函数能保存函数创建时的this值,而不是调用时的值。
泛型
创建可重用的组件,
function identity(arg:T): T {
return arg;
}泛型类型
interface GenericldentityFn {
(arg: T): T;
}
function identity(arg:T):T {
return arg;
}
let myldentity: GenericldentityFn = identity;泛型类
















