TypeScript官方指导文档:https://www.tslang.cn/docs/home.html
基本类型
变量声明
使用let
和const两个关键字声明变量,具体形式如下:
let user = "Jane User";
接口定义
interface SquareConfig {
color?: string;//?代表可选属性
width?: number;
readonly x: number;//readonly 表示只读属性
readonly y: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
let newSquare = {color: "white", area: 100};
if (config.clor) {
// Error: Property 'clor' does not exist on type 'SquareConfig'
newSquare.color = config.clor;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
类定义
abstract class Department {
constructor(public name: string) {
}
printName(): void {
console.log('Department name: ' + this.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 reports...');
}
}
let department: Department; // 允许创建一个对抽象类型的引用
department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
department.printName();
department.printMeeting();
department.generateReports(); // 错误: 方法在声明的抽象类中不存在
相关知识点:
class关键字,继承关键字extends,公有public、私有private与受保护protected的修饰符,只读属性修饰符readonly、静态属性static、getters/setters存取器、抽象类abstract、
函数定义
// Named function
function add(x, y) {
return x + y;
}
// Anonymous function
let myAdd = function(x, y) { return x + y; };
相关知识点:
有名函数、匿名函数、可选参数、默认参数、剩余参数、