TypeScript—语法简介
生活随笔
收集整理的這篇文章主要介紹了
TypeScript—语法简介
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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; };相關知識點:
有名函數、匿名函數、可選參數、默認參數、剩余參數、
?
?
?
?
?
?
?
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的TypeScript—语法简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TypeScript—快速入门
- 下一篇: node.js和npm的关系