TypeScript基础教程
TypeScript基础教程
TypeScript简介
TypeScript是微软开发的一种开源编程语言,它是JavaScript的超集,添加了可选的静态类型和基于类的面向对象编程。TypeScript在编译时提供类型检查,可以在开发阶段就发现潜在错误,提高代码质量和开发效率。
TypeScript的优势
- 静态类型检查:捕获开发阶段的错误
- 增强的IDE支持:提供代码补全和智能提示
- ES6+特性支持:支持最新的JavaScript特性
- 面向对象编程:提供类、接口、继承等OOP特性
- 大型项目可维护性:类型系统使大型项目更易于维护和重构
环境搭建
安装Node.js和npm
首先需要安装Node.js和npm,可以从Node.js官网下载安装包。
安装TypeScript
安装完Node.js后,使用npm全局安装TypeScript:
npm install -g typescript
验证安装成功:
tsc --version
创建第一个TypeScript文件
- 创建一个名为
hello.ts
的文件:
function greet(name: string) {
return `Hello, ${name}!`;
}
console.log(greet("TypeScript"));
- 编译TypeScript文件:
tsc hello.ts
这将生成hello.js
文件。
- 运行JavaScript文件:
node hello.js
基本类型
TypeScript支持多种数据类型:
布尔值
let isDone: boolean = false;
数字
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
字符串
let color: string = "blue";
let fullName: string = `Bob Bobbington`;
let sentence: string = `Hello, my name is ${fullName}`;
数组
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3]; // 泛型数组类型
元组
let x: [string, number];
x = ["hello", 10]; // 正确
x = [10, "hello"]; // 错误
枚举
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
Any
let notSure: any = 4;
notSure = "maybe a string";
notSure = false; // 也可以是布尔值
Void
function warnUser(): void {
console.log("This is a warning message");
}
Null和Undefined
let u: undefined = undefined;
let n: null = null;
Never
function error(message: string): never {
throw new Error(message);
}
Unknown
let value: unknown;
value = true; // OK
value = 42; // OK
变量声明
TypeScript支持JavaScript的var
、let
和const
关键字,但推荐使用let
和const
。
let hello = "Hello!";
const PI = 3.14159;
类型断言
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// 或
let strLength2: number = (someValue as string).length;
函数
函数类型
function add(x: number, y: number): number {
return x + y;
}
// 函数类型表达式
let myAdd: (x: number, y: number) => number = function(x, y) { return x + y; };
可选参数和默认参数
function buildName(firstName: string, lastName?: string): string {
return lastName ? firstName + " " + lastName : firstName;
}
function buildName2(firstName: string, lastName = "Smith"): string {
return firstName + " " + lastName;
}
剩余参数
function buildName(firstName: string, ...restOfName: string[]): string {
return firstName + " " + restOfName.join(" ");
}
接口
接口定义了对象的结构和约束。
interface Person {
firstName: string;
lastName: string;
age?: number; // 可选属性
readonly id: number; // 只读属性
}
function greet(person: Person) {
return `Hello, ${person.firstName} ${person.lastName}`;
}
let user: Person = {
firstName: "John",
lastName: "Doe",
id: 1
};
实现接口
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
类
TypeScript提供了基于类的面向对象编程支持。
class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
bark() {
console.log('Woof! Woof!');
}
move(distanceInMeters = 5) {
console.log("Running...");
super.move(distanceInMeters);
}
}
const dog = new Dog("Rex");
dog.bark();
dog.move(10);
访问修饰符
class Animal {
private name: string;
protected age: number;
public color: string;
constructor(name: string, age: number, color: string) {
this.name = name;
this.age = age;
this.color = color;
}
}
静态属性
class Grid {
static origin = {x: 0, y: 0};
calculateDistanceFromOrigin(point: {x: number; y: number;}) {
let xDist = point.x - Grid.origin.x;
let yDist = point.y - Grid.origin.y;
return Math.sqrt(xDist * xDist + yDist * yDist);
}
}
泛型
泛型允许创建可重用的组件,适用于多种类型而不是单一类型。
function identity<T>(arg: T): T {
return arg;
}
// 调用泛型函数
let output = identity<string>("myString");
// 或者使用类型推断
let output2 = identity("myString");
泛型接口
interface GenericIdentityFn<T> {
(arg: T): T;
}
let myIdentity: GenericIdentityFn<number> = identity;
泛型类
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
模块与命名空间
导出
// 文件: math.ts
export function add(x: number, y: number): number {
return x + y;
}
导入
// 文件: main.ts
import { add } from "./math";
console.log(add(1, 2));
命名空间
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export class LettersOnlyValidator implements StringValidator {
isAcceptable(s: string) {
return /^[A-Za-z]+$/.test(s);
}
}
}
let validator = new Validation.LettersOnlyValidator();
TypeScript配置
创建tsconfig.json
文件配置TypeScript编译选项:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "dist"
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
实战示例
创建一个简单的待办事项应用
// 定义Todo接口
interface Todo {
id: number;
title: string;
completed: boolean;
}
// 创建TodoApp类
class TodoApp {
private todos: Todo[] = [];
private nextId: number = 1;
addTodo(title: string): Todo {
const todo: Todo = {
id: this.nextId++,
title,
completed: false
};
this.todos.push(todo);
return todo;
}
toggleTodo(id: number): Todo | undefined {
const todo = this.getTodo(id);
if (todo) {
todo.completed = !todo.completed;
return todo;
}
return undefined;
}
removeTodo(id: number): boolean {
const initialLength = this.todos.length;
this.todos = this.todos.filter(todo => todo.id !== id);
return initialLength !== this.todos.length;
}
getTodo(id: number): Todo | undefined {
return this.todos.find(todo => todo.id === id);
}
getAllTodos(): Todo[] {
return this.todos;
}
}
// 使用TodoApp
const app = new TodoApp();
app.addTodo("学习TypeScript");
app.addTodo("创建项目");
const todo3 = app.addTodo("发布应用");
app.toggleTodo(2); // 将"创建项目"标记为已完成
console.log(app.getAllTodos());
这个教程涵盖了TypeScript的基础知识。要深入学习TypeScript,建议参考TypeScript官方文档和其他进阶资源。