TypeScript 是 JavaScript 的类型超集,可编译为纯 JavaScript。它将静态类型添加到您的代码中,从而更容易在开发过程中捕获错误。
设置 TypeScript
首先,让我们设置 TypeScript:
npm install -g typescript
tsc --init
要编译 TypeScript 文件 (.ts),请运行:
tsc filename.ts
让我们从一些基本类型和有趣的例子开始。
let greeting: string = "Hello, TypeScript!"; console.log(greeting); // Hello, TypeScript!
let age: number = 42; console.log(`I'm ${age} years old!`); // I'm 42 years old!
let isHappy: boolean = true; console.log(`Am I happy? ${isHappy}`); // Am I happy? true
想象一个只能理解特定类型的机器人:
let robotName: string = "RoboCop"; let robotAge: number = 100; let isRobotFriendly: boolean = true; console.log(`Meet ${robotName}, who is ${robotAge} years old. Friendly? ${isRobotFriendly}`); // Meet RoboCop, who is 100 years old. Friendly? true
TypeScript 数组只能保存一种类型的数据:
let fruits: string[] = ["Apple", "Banana", "Cherry"]; console.log(fruits); // ["Apple", "Banana", "Cherry"]
一只猫整理它的玩具收藏(只有球):
let catToys: string[] = ["Ball1", "Ball2", "Ball3"]; console.log(catToys); // ["Ball1", "Ball2", "Ball3"]
元组允许您表达具有固定数量且类型已知的元素的数组:
let myTuple: [string, number]; myTuple = ["Hello", 42]; // OK console.log(myTuple); // ["Hello", 42]
想象一个具有代号和 ID 号的超级特工:
let agent: [string, number] = ["Bond", 007]; console.log(agent); // ["Bond", 007]
TypeScript 允许您指定函数的参数类型和返回值。
function add(a: number, b: number): number { return a + b; } console.log(add(5, 3)); // 8
拿着魔勺的厨师:
function mixIngredients(ingredient1: string, ingredient2: string): string { return `${ingredient1} mixed with ${ingredient2}`; } console.log(mixIngredients("Flour", "Sugar")); // Flour mixed with Sugar
接口定义对象的结构。
interface Person { name: string; age: number; } let user: Person = { name: "Alice", age: 30 }; console.log(user); // { name: "Alice", age: 30 }
一只会说话的狗,有一张特殊的身份证:
interface Dog { name: string; breed: string; } let talkingDog: Dog = { name: "Scooby-Doo", breed: "Great Dane" }; console.log(talkingDog); // { name: "Scooby-Doo", breed: "Great Dane" }
TypeScript 类是创建具有初始值和方法的对象的蓝图。
class Animal { name: string; constructor(name: string) { this.name = name; } move(distance: number = 0) { console.log(`${this.name} moved ${distance} meters.`); } } let dog = new Animal("Dog"); dog.move(10); // Dog moved 10 meters.
超级英雄课程:
class Superhero { name: string; constructor(name: string) { this.name = name; } saveTheCat() { console.log(`${this.name} saved the cat!`); } } let hero = new Superhero("Batman"); hero.saveTheCat(); // Batman saved the cat!
枚举允许我们定义一组命名常量。
enum Direction { Up, Down, Left, Right } let move: Direction = Direction.Up; console.log(move); // 0
交通灯系统:
enum TrafficLight { Red, Yellow, Green } let light: TrafficLight = TrafficLight.Green; console.log(light); // 2
_您刚刚快速浏览了 TypeScript,从基本类型到泛型和枚举等更高级的功能。通过这些示例,您应该有一个良好的起点,可以在项目中进一步探索和使用 TypeScript。
如果您有任何具体问题或需要有关 TypeScript 任何部分的更多有趣示例,请随时询问!_
以上是TypeScript 简介的详细内容。更多信息请关注PHP中文网其他相关文章!