【进阶 TypeScript 开发】探秘高级技巧,助您成为 TypeScript 强者!

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: HELLO
logMessage(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: 90
console.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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值