1. TypeScript概述
TypeScript是JavaScript的超集,添加了静态类型系统和其他特性,使得代码更加健壮、可维护。TypeScript由Microsoft开发,是前端开发中越来越受欢迎的语言。更多学习教程www.fgedu.net.cn
TypeScript的主要特点包括:
- 静态类型:在编译时检查类型错误
- 面向对象:支持类、接口、继承等面向对象特性
- 类型推断:自动推断变量类型
- 工具支持:提供更好的IDE支持,包括代码补全、重构等
- 向后兼容:完全兼容JavaScript,可以逐步迁移
2. TypeScript环境搭建
搭建TypeScript开发环境需要安装Node.js和TypeScript编译器。
npm install -g typescript
# 检查TypeScript版本
ts –version
# 创建TypeScript配置文件
tsconfig.json
{
“compilerOptions”: {
“target”: “es5”,
“module”: “commonjs”,
“strict”: true,
“esModuleInterop”: true,
“skipLibCheck”: true,
“forceConsistentCasingInFileNames”: true
}
}
# 编译TypeScript文件
ts file.ts
# 监视文件变化并自动编译
ts –watch file.ts
npm init -y
# 安装TypeScript作为开发依赖
npm install –save-dev typescript
# 添加编译脚本到package.json
{
“scripts”: {
“build”: “tsc”,
“watch”: “tsc –watch”
}
}
# 运行编译
npm run build
# 运行监视模式
npm run watch
3. TypeScript类型系统
TypeScript提供了丰富的类型系统,包括基本类型、联合类型、交叉类型等。学习交流加群风哥微信: itpux-com
3.1 基本类型
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 age: number = 37;
let sentence: string = `Hello, my name is ${fullName}. I’ll be ${age + 1} years old next month.`;
// 数组
let list: number[] = [1, 2, 3];
let list: Array
// 元组
let x: [string, number];
x = [“hello”, 10]; // OK
x = [10, “hello”]; // Error
// 枚举
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
// Any
let notSure: any = 4;
notSure = “maybe a string instead”;
notSure = false; // okay, definitely a boolean
// Void
function warnUser(): void {
console.log(“This is my warning message”);
}
// Null and Undefined
let u: undefined = undefined;
let n: null = null;
// Never
function error(message: string): never {
throw new Error(message);
}
3.2 类型断言
let someValue: any = “this is a string”;
let strLength: number = (someValue as string).length;
let strLength: number = (
4. 接口(Interfaces)
接口用于定义对象的结构,指定对象应该具有哪些属性和方法。
interface Person {
firstName: string;
lastName: string;
}
function greet(person: Person) {
return “Hello, ” + person.firstName + ” ” + person.lastName;
}
let user = {
firstName: “John”,
lastName: “Doe”
};
console.log(greet(user));
// 可选属性
interface Person {
firstName: string;
lastName: string;
age?: number;
}
// 只读属性
interface Person {
readonly id: number;
firstName: string;
lastName: string;
}
// 函数类型
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc = function(source: string, subString: string): boolean {
let result = source.search(subString);
return result > -1;
};
// 可索引类型
interface StringArray {
[index: number]: string;
}
let myArray: StringArray = [“Bob”, “Fred”];
5. 类(Classes)
TypeScript支持ES6的类语法,并添加了类型注解和访问修饰符。
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return “Hello, ” + this.greeting;
}
}
let greeter = new Greeter(“world”);
console.log(greeter.greet());
// 继承
class Animal {
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
bark() {
console.log(“Woof! Woof!”);
}
}
const dog = new Dog();
dog.bark();
dog.move(10);
dog.bark();
// 访问修饰符
class Employee {
private name: string;
protected department: string;
public position: string;
constructor(name: string, department: string, position: string) {
this.name = name;
this.department = department;
this.position = position;
}
getName() {
return this.name;
}
}
class Manager extends Employee {
constructor(name: string, department: string) {
super(name, department, “Manager”);
}
getDepartment() {
return this.department;
}
}
// 静态属性
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);
}
constructor(public scale: number) {}
}
let grid1 = new Grid(1.0);
let grid2 = new Grid(5.0);
console.log(grid1.calculateDistanceFromOrigin({ x: 10, y: 10 }));
console.log(grid2.calculateDistanceFromOrigin({ x: 10, y: 10 }));
6. 泛型(Generics)
泛型允许创建可重用的组件,这些组件可以与多种类型一起工作,而不是单一类型。学习交流加群风哥QQ113257174
function identity
return arg;
}
let output1 = identity
let output2 = identity
let output3 = identity(“myString”); // 类型推断
// 泛型接口
interface GenericIdentityFn
(arg: T): T;
}
function identity
return arg;
}
let myIdentity: GenericIdentityFn
// 泛型类
class GenericNumber
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
let stringNumeric = new GenericNumber
stringNumeric.zeroValue = “”;
stringNumeric.add = function(x, y) { return x + y; };
// 泛型约束
interface Lengthwise {
length: number;
}
function loggingIdentity
console.log(arg.length);
return arg;
}
loggingIdentity(“hello”); // OK
loggingIdentity([1, 2, 3]); // OK
loggingIdentity(42); // Error
7. 模块(Modules)
TypeScript支持模块系统,允许将代码分割成可重用的部分。
export interface StringValidator {
isAcceptable(s: string): boolean;
}
export const numberRegexp = /^[0-9]+$/;
export class ZipCodeValidator implements StringValidator {
isAcceptable(s: string) {
return s.length === 5 && numberRegexp.test(s);
}
}
// 导入模块
import { StringValidator, ZipCodeValidator, numberRegexp } from “./validators”;
let myValidator = new ZipCodeValidator();
console.log(myValidator.isAcceptable(“12345”));
// 导入整个模块
import * as validator from “./validators”;
let myValidator = new validator.ZipCodeValidator();
console.log(myValidator.isAcceptable(“12345”));
// 默认导出
export default class DefaultValidator {
isAcceptable(s: string) {
return s.length > 0;
}
}
// 导入默认导出
import DefaultValidator from “./defaultValidator”;
let myValidator = new DefaultValidator();
console.log(myValidator.isAcceptable(“hello”));
8. 高级特性
TypeScript提供了一些高级特性,如类型别名、交叉类型、联合类型等。
8.1 类型别名
type StringOrNumber = string | number;
type UserInput = string | number | boolean;
type Point = {
x: number;
y: number;
};
function printCoord(pt: Point) {
console.log(`The coordinate’s x value is ${pt.x}`);
console.log(`The coordinate’s y value is ${pt.y}`);
}
printCoord({ x: 100, y: 100 });
8.2 交叉类型
interface A {
a: number;
}
interface B {
b: string;
}
type C = A & B;
let c: C = {
a: 1,
b: “hello”
};
8.3 联合类型
function padLeft(value: string, padding: string | number) {
if (typeof padding === “number”) {
return Array(padding + 1).join(” “) + value;
}
if (typeof padding === “string”) {
return padding + value;
}
throw new Error(`Expected string or number, got ‘${typeof padding}’.`);
}
console.log(padLeft(“Hello world”, 4));
console.log(padLeft(“Hello world”, ” “));
8.4 类型守卫
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
if (isFish(pet)) {
pet.swim();
} else {
pet.fly();
}
// typeof类型守卫
function isNumber(x: any): x is number {
return typeof x === “number”;
}
// instanceof类型守卫
function isDate(obj: any): obj is Date {
return obj instanceof Date;
}
9. TypeScript最佳实践
遵循TypeScript最佳实践可以提高代码质量和可维护性。更多学习教程公众号风哥教程itpux_com
9.1 类型使用
- 使用具体类型而不是any
- 使用类型别名和接口组织类型
- 使用泛型提高代码复用性
- 使用类型守卫处理联合类型
9.2 配置最佳实践
{
“compilerOptions”: {
“target”: “es2018”,
“module”: “commonjs”,
“lib”: [“es2018”],
“strict”: true,
“esModuleInterop”: true,
“skipLibCheck”: true,
“forceConsistentCasingInFileNames”: true,
“declaration”: true,
“sourceMap”: true,
“outDir”: “./dist”,
“rootDir”: “./src”
},
“include”: [“src/**/*”],
“exclude”: [“node_modules”, “dist”]
}
9.3 代码组织
- 按功能组织文件和目录
- 使用模块导出和导入
- 使用命名空间组织相关代码
- 使用装饰器增强类的功能
9.4 性能优化
- 使用类型断言避免不必要的类型检查
- 使用const断言提高性能
- 使用延迟加载减少初始加载时间
- 使用tree-shaking减少打包体积
TypeScript是一种强大的编程语言,通过静态类型系统和其他特性,使得代码更加健壮、可维护。掌握TypeScript的基础知识,结合现代前端工具和最佳实践,可以创建出高质量、类型安全的前端应用。author:www.itpux.com
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
