欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

15個用于開發(fā)的TypeScript高級技巧分享

 更新時間:2023年07月25日 09:03:39   作者:王大冶  
這篇文章主要來和大家分享一下15個用于開發(fā)的TypeScript高級技巧,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以了解一下

1.可選鏈 (?.)

可選鏈允許你安全地訪問嵌套屬性或方法,無需擔(dān)心 nullundefined 值。如果任何中間屬性為 nullundefined,它會立即終止評估。

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 時提供默認(rèn)值。

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.Generics

泛型使我們能夠創(chuàng)建可與各種類型一起使用的可重用組件。

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操作符返回給定類型的所有已知屬性名稱的聯(lián)合。

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.類型守衛(wèi)

類型保護(hù)允許你根據(jù)特定條件,在條件塊中縮小變量的類型范圍。

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.交叉類型

交叉類型允許我們將多個類型組合成一個單一類型,創(chuàng)建一個新類型,該類型具有交叉類型的所有屬性和方法。

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.映射類型

映射類型允許我們通過轉(zhuǎn)換現(xiàn)有類型的屬性來創(chuàng)建新類型。

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.字符串字面類型和聯(lián)合類型:

TypeScript支持字符串字面量類型和聯(lián)合類型,可以用于為變量定義特定的值集合。

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

裝飾器允許我們修改或擴(kuò)展類、方法、屬性和其他聲明的行為。

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.索引簽名

索引簽名允許我們在接口或類型中定義動態(tài)屬性名稱及其對應(yīng)的類型。

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可以根據(jù)條件語句推斷類型,從而使代碼更加簡潔。

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 修飾符來定義在初始化后無法修改的屬性。

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.類型別名

類型別名允許我們?yōu)楝F(xiàn)有類型創(chuàng)建自定義名稱,提供更多的語義含義并提高代碼的可讀性。

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. 類型守衛(wèi)與類

類型保護(hù)也可以與類一起使用,以縮小對象實例的類型范圍。

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

到此這篇關(guān)于15個用于開發(fā)的TypeScript高級技巧分享的文章就介紹到這了,更多相關(guān)TypeScript技巧內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論