15个用于开发的高级TypeScript技巧

2023-08-16 08:17:25 浏览数 (1)

可选链 (?.)

可选链允许你安全地访问嵌套属性或方法,无需担心 nullundefined 值。如果任何中间属性为 nullundefined,它会立即终止评估。

代码语言:javascript复制
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.空值合并运算符 (??)

空值合并运算符在变量为 null 或 undefined 时提供默认值。

代码语言:javascript复制
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无法推断变量类型时,显式地定义变量的类型。

代码语言:javascript复制
const userInput: unknown = 'Hello World';
const strLength = (userInput as string).length;
console.log(strLength); // Output: 11

4.Generics

泛型使我们能够创建可与各种类型一起使用的可重用组件。

代码语言:javascript复制
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操作符返回给定类型的所有已知属性名称的联合。

代码语言:javascript复制
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.类型守卫

类型保护允许你根据特定条件,在条件块中缩小变量的类型范围。

代码语言:javascript复制
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.交叉类型

交叉类型允许我们将多个类型组合成一个单一类型,创建一个新类型,该类型具有交叉类型的所有属性和方法。

代码语言:javascript复制
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.映射类型

映射类型允许我们通过转换现有类型的属性来创建新类型。

代码语言:javascript复制
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支持字符串字面量类型和联合类型,可以用于为变量定义特定的值集合。

代码语言:javascript复制
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

装饰器允许我们修改或扩展类、方法、属性和其他声明的行为。

代码语言:javascript复制
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.索引签名

索引签名允许我们在接口或类型中定义动态属性名称及其对应的类型。

代码语言:javascript复制
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可以根据条件语句推断类型,从而使代码更加简洁。

代码语言:javascript复制
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.只读属性

TypeScript 提供了 readonly 修饰符来定义在初始化后无法修改的属性。

代码语言:javascript复制
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.类型别名

类型别名允许我们为现有类型创建自定义名称,提供更多的语义含义并提高代码的可读性。

代码语言:javascript复制
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. 类型守卫与类

类型保护也可以与类一起使用,以缩小对象实例的类型范围。

代码语言:javascript复制
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 人点赞