【专业 TypeScript 实战】15 个高级技巧,开创卓越开发之路!
作者:汽车之家客户端前端团队
- 2023-07-25 北京
本文字数:3274 字
阅读完需:约 11 分钟

1.可选链接(?.):
可选链允许您安全地访问嵌套的属性或方法,而无需担心空值或未定义值。它会在任何中间属性为 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: undefined
复制代码
2.空值合并运算符(??):
空值合并运算符在变量为空或未定义时提供默认值。
const name = null;const defaultName = name ?? 'Unknown';console.log(defaultName); // Output: Unknown
const age = 0;const defaultAge = age ?? 18;console.log(defaultAge); // Output: 0
复制代码
3.类型断言:
类型断言允许您在 TypeScript 无法推断变量类型时明确定义变量的类型
const userInput: unknown = 'Hello World';const strLength = (userInput as string).length;console.log(strLength); // Output: 11
复制代码
4.泛型:
泛型使您能够创建可与各种类型一起使用的可重用组件。
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: HELLOlogMessage(3.14159); // Output: Value: 3.14
复制代码
7.交叉类型:
交叉类型允许您将多个类型合并为一个类型,创建一个新类型,该新类型具有交叉类型的所有属性和方法。
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 data
复制代码
8.映射类型:
映射类型允许您通过转换现有类型的属性来创建新类型。您可以根据现有类型的属性生成新的类型,例如将属性变为可选或只读,添加或移除属性等。映射类型提供了一种方便的方式来生成类型的变体,以适应特定的需求。
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.装饰器:
装饰器允许您修改或扩展类、方法、属性和其他声明的行为。
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 DOE
复制代码
11.索引签名:
索引签名允许您在接口或类型中定义动态属性名称及其对应的类型。
interface Dictionary { [key: string]: number;}
const scores: Dictionary = { math: 90, science: 85, history: 95};
console.log(scores['math']); // Output: 90console.log(scores['english']); // Output: undefined
复制代码
12.使用条件语句进行类型推断:
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.00
复制代码
13.Readonly 属性:
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.53981633974483
复制代码
14.类型别名:
类型别名允许您为现有类型创建自定义名称,提供更多语义并提高代码可读性。
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
复制代码
划线
评论
复制
发布于: 刚刚阅读数: 3
汽车之家客户端前端团队
关注
前端技术创新 体验优化 分享经验 共同进步 2018-11-25 加入
通过技术的创新和优化,为用户创造更好的使用体验,并与更多的前端开发者分享我们的经验和成果。我们欢迎对前端开发感兴趣的朋友加入我们的团队,一同探讨技术,共同进步。










评论