TypeScript高级特性:提升代码质量
TypeScript高级特性:提升代码质量
TypeScript是JavaScript的超集,提供了强大的类型系统。掌握高级特性能够写出更安全、更可维护的代码。
泛型编程
基本泛型
function identity<T>(arg: T): T { return arg } const num = identity<number>(42) const str = identity<string>('hello')泛型约束
interface Lengthwise { length: number } function logLength<T extends Lengthwise>(arg: T): T { console.log(arg.length) return arg }泛型类
class Container<T> { private items: T[] = [] add(item: T) { this.items.push(item) } get(index: number): T | undefined { return this.items[index] } }类型体操
条件类型
type IsString<T> = T extends string ? true : false type A = IsString<string> // true type B = IsString<number> // false映射类型
type Readonly<T> = { readonly [P in keyof T]: T[P] } type Partial<T> = { [P in keyof T]?: T[P] }模板字面量类型
type Color = 'red' | 'green' | 'blue' type Size = 'small' | 'medium' | 'large' type ColorSize = `${Color}-${Size}` // 'red-small' | 'red-medium' | 'red-large' | ...高级类型技巧
infer关键字
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never type Fn = () => string type Result = ReturnType<Fn> // string条件类型嵌套
type DeepReadonly<T> = { readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P] }装饰器
类装饰器
function sealed(constructor: Function) { Object.seal(constructor) Object.seal(constructor.prototype) } @sealed class Greeter { greeting: string constructor(message: string) { this.greeting = message } }属性装饰器
function format(target: any, propertyKey: string) { let value = target[propertyKey] const getter = () => value const setter = (newValue: string) => { value = newValue.toUpperCase() } Object.defineProperty(target, propertyKey, { get: getter, set: setter, enumerable: true, configurable: true }) } class User { @format name: string }模块系统
ES模块
// utils.ts export function add(a: number, b: number): number { return a + b } // app.ts import { add } from './utils'命名空间
namespace Validation { export function validateEmail(email: string): boolean { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) } } Validation.validateEmail('test@example.com')类型声明
声明文件
// module.d.ts declare module 'some-module' { export function doSomething(): void }合并声明
interface User { name: string } interface User { age: number } // User now has both name and age编译器配置
tsconfig.json
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true } }总结
TypeScript的高级特性能够帮助我们写出更安全、更可维护的代码。掌握这些特性,能够提升我们的开发效率和代码质量。
技术有温度,TypeScript让代码更加健壮和可靠。
