本文深入解析TypeScript开发的15个高级技巧,涵盖可选链、空值合并、类型断言、泛型、keyof运算符、类型守卫、交叉类型、映射类型、字符串字面类型、装饰器、索引签名、条件类型推断、只读属性、类型别名及类类型保护。通过具体代码示例,帮助开发者提升代码安全性、可维护性与复用性,适用于中高级前端与全栈开发场景。
1.可选链 (?.)
借助可选链操作符,可安全访问嵌套属性或方法,无需担忧 null 或 undefined 值。若中间属性为 null 或 undefined,则立即终止求值。
const user = {
name: 'John',
address: {
city: 'New York',
postalCode: '12345'
}
};
const postalCode = user.address?.postalCode;
console.log(postalCode); // Output: 12345
const invalidCode = user.address?.postalCode?.toLowerCase();
console.log(invalidCode); // Output: undefined2.空值合并运算符 (??)
当变量值为 null 或 undefined 时,空值合并运算符用于提供默认值。
const name = null;
const defaultName = name ?? 'Unknown';
console.log(defaultName); // Output: Unknown
const age = 0;
const defaultAge = age ?? 18;
console.log(defaultAge); // Output: 03.类型断言
在 TypeScript 无法推断变量类型时,类型断言允许显式指定变量类型。
const userInput: unknown = 'Hello World';
const strLength = (userInput as string).length;
console.log(strLength); // Output: 114.Generics
泛型支持创建可与多种类型配合使用的可复用组件。
function reverse<T>(items: T[]): T[] {
return items.reverse();
}
const numbers = [1, 2, 3, 4, 5];
const reversedNumbers = reverse(numbers);
console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]
const strings = ['a', 'b', 'c'];
const reversedStrings = reverse(strings);
console.log(reversedStrings); // Output: ['c', 'b', 'a']5. keyof 运算符
keyof操作符返回指定类型中所有已知属性名的联合类型。
interface User {
id: number;
name: string;
email: string;
}
function getUserProperty(user: User, property: keyof User) {
return user[property];
}
const user: User = {
id: 1,
name: 'John Doe',
email: 'john@example.com'
};
const name = getUserProperty(user, 'name');
console.log(name); // Output: John Doe
const invalidProperty = getUserProperty(user, 'age'); // Error: Argument of type '"age"' is not assignable to parameter of type '"id" | "name" | "email"'6.类型守卫
类型保护允许依据特定条件,在条件块内缩小变量类型范围。
function logMessage(message: string | number) {
if (typeof message === 'string') {
console.log('Message: ' + message.toUpperCase());
} else {
console.log('Value: ' + message.toFixed(2));
}
}
logMessage('hello'); // Output: Message: HELLO
logMessage(3.14159); // Output: Value: 3.147.交叉类型
交叉类型可将多个类型合并为单一类型,生成包含所有源类型属性和方法的新类型。
interface Loggable {
log: () => void;
}
interface Serializable {
serialize: () => string;
}
type Logger = Loggable & Serializable;
class ConsoleLogger implements Loggable {
log() {
console.log('Logging to console...');
}
}
class FileLogger implements Loggable, Serializable {
log() {
console.log('Logging to file...');
}
serialize() {
return 'Serialized log data';
}
}
const logger1: Logger = new ConsoleLogger();
logger1.log(); // Output: Logging to console...
const logger2: Logger = new FileLogger();
logger2.log(); // Output: Logging to file...
console.log(logger2.serialize()); // Output: Serialized log data8.映射类型
映射类型允许通过转换现有类型的属性来构建新类型。
interface User {
id: number;
name: string;
email: string;
}
type PartialUser = { [K in keyof User]?: User[K] };
const partialUser: PartialUser = {
name: 'John Doe',
email: 'john@example.com'
};
console.log(partialUser); // Output: { name: 'John Doe', email: 'john@example.com' }9.字符串字面类型和联合类型:
TypeScript 支持字符串字面量类型与联合类型,可用于为变量限定特定值集合。
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
function sendRequest(url: string, method: HttpMethod) {
// send request logic here...
}
sendRequest('/users', 'GET');
sendRequest('/users', 'POST');
sendRequest('/users/1', 'PUT');
sendRequest('/users/1', 'DELETE');10.Decorators
装饰器允许修改或扩展类、方法、属性及其他声明的行为。
function uppercase(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 Person {
@uppercase
name: string;
}
const person = new Person();
person.name = 'John Doe';
console.log(person.name); // Output: JOHN DOE11.索引签名
索引签名允许在接口或类型定义中指定动态属性名称及其对应类型。
interface Dictionary {
[key: string]: number;
}
const scores: Dictionary = {
math: 90,
science: 85,
history: 95
};
console.log(scores['math']); // Output: 90
console.log(scores['english']); // Output: undefined12. 条件语句中的类型推断
TypeScript 可根据条件语句推断类型,从而简化代码。
function calculateTax(amount: number, isTaxable: boolean) {
if (isTaxable) {
return amount * 1.1; // Type: number
} else {
return amount; // Type: number
}
}
const taxableAmount = calculateTax(100, true);
console.log(taxableAmount.toFixed(2)); // Output: 110.00
const nonTaxableAmount = calculateTax(100, false);
console.log(nonTaxableAmount.toFixed(2)); // Output: 100.0013.只读属性
TypeScript 提供了 readonly 修饰符,用于定义初始化后不可修改的属性。
class Circle {
readonly radius: number;
constructor(radius: number) {
this.radius = radius;
}
getArea() {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle(5);
console.log(circle.radius); // Output: 5
// circle.radius = 10; // Error: Cannot assign to 'radius' because it is a read-only property
console.log(circle.getArea()); // Output: 78.5398163397448314.类型别名
类型别名允许为现有类型创建自定义名称,以增强语义含义并提升代码可读性。
type Point = {
x: number;
y: number;
};
type Shape = 'circle' | 'square' | 'triangle';
function draw(shape: Shape, position: Point) {
console.log(`Drawing a ${shape} at (${position.x}, ${position.y})`);
}
const startPoint: Point = { x: 10, y: 20 };
draw('circle', startPoint); // Output: Drawing a circle at (10, 20)15. 类型守卫与类
类型保护亦可与类结合使用,以缩小对象实例的类型范围。
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Dog extends Animal {
bark() {
console.log('Woof!');
}
}
function makeSound(animal: Animal) {
if (animal instanceof Dog) {
animal.bark(); // Type: Dog
} else {
console.log('Unknown animal');
}
}
const dog = new Dog('Buddy');
const animal = new Animal('Unknown');
makeSound(dog); // Output: Woof!
makeSound(animal); // Output: Unknown animal到此这篇关于15个用于开发的TypeScript高级技巧分享的文章就介绍到这了,更多相关TypeScript技巧内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!