新聞中心
TypeScript 是一種由微軟開發(fā)的開源編程語(yǔ)言,它是 JavaScript 的一個(gè)超集,添加了可選的靜態(tài)類型和基于類的面向?qū)ο缶幊?,TypeScript 的設(shè)計(jì)目標(biāo)是提高代碼的可讀性和可維護(hù)性,同時(shí)保持對(duì) JavaScript 的兼容性,在許多方面,TypeScript 都可以被視為是 JavaScript 的一個(gè)更好的版本。

TypeScript 基礎(chǔ)
安裝 TypeScript
要開始使用 TypeScript,首先需要在計(jì)算機(jī)上安裝它,可以通過(guò) Node.js 包管理器 npm 來(lái)安裝 TypeScript:
npm install g typescript
TypeScript 文件
創(chuàng)建一個(gè)名為 example.ts 的文件,然后在其中輸入以下內(nèi)容:
function greeter(person: string) {
return "Hello, " + person;
}
let user = "TypeScript User";
console.log(greeter(user));
這個(gè)文件定義了一個(gè)名為 greeter 的函數(shù),該函數(shù)接受一個(gè)字符串參數(shù) person,并返回一個(gè)問(wèn)候語(yǔ),我們創(chuàng)建了一個(gè)名為 user 的變量,并將其值設(shè)置為 "TypeScript User",我們調(diào)用 greeter 函數(shù)并將結(jié)果打印到控制臺(tái)。
編譯 TypeScript 文件
要編譯 TypeScript 文件,需要使用 tsc 命令:
tsc example.ts
這將生成一個(gè)名為 example.js 的 JavaScript 文件,可以使用 Node.js 來(lái)運(yùn)行此文件:
node example.js
輸出應(yīng)該是:
Hello, TypeScript User
TypeScript 特性
類型注解
TypeScript 支持兩種類型的注解:尖括號(hào)(<>)和方括號(hào)([]),尖括號(hào)表示具體的類型,而方括號(hào)表示任意類型。
let numbers: number[] = [1, 2, 3]; // 數(shù)組中的所有元素都是數(shù)字類型 let strings: string[] = ["TypeScript", "Rocks"]; // 同上 let mixed: (number | string)[] = [1, "two", 3, "four"]; // 混合類型數(shù)組,可以包含數(shù)字和字符串類型
接口
接口是一種描述對(duì)象結(jié)構(gòu)的方式,它們可以用來(lái)檢查一個(gè)對(duì)象是否具有特定的屬性和方法。
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person): void {
console.log("Hello, " + person.firstName + " " + person.lastName);
}
類和對(duì)象繼承
TypeScript 支持類和對(duì)象繼承。
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distanceInMeters: number = 0) {
console.log(${this.name} moved ${distanceInMeters}m.);
}
}
class Dog extends Animal {
bark() {
console.log("Woof!");
}
}
const dog = new Dog("Rufus");
dog.bark(); // Woof!
dog.move(10); // Rufus moved 10m. without specifying distance in meters. default value is used. and then the method of the parent class is called. which prints the output as mentioned above. but if we call the move method with a distance, it will be called from the Dog class and not from the Animal class. because of the way JavaScript works with classes and objects. and that's why we need to use the super keyword to call the method from the parent class. like this: dog.super.move(10); // Rufus moved 10m. which is the expected output. and now we have achieved our goal of calling the method from the parent class when needed. even though we are using an ES6 class syntax. which is similar to TypeScript classes. but they are not exactly the same thing. and there are some differences between them as well. which we will discuss later in this tutorial. on advanced topics section. where we will cover more complex topics related to TypeScript and its features. such as decorators, modules, async/await, etc...
文章標(biāo)題:TypeScript輸入輸出
當(dāng)前地址:http://m.fisionsoft.com.cn/article/cdjdccg.html


咨詢
建站咨詢
