15個用于開發(fā)的TypeScript高級技巧分享
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: 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)
類型保護允許你根據(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.147.交叉類型
交叉類型允許我們將多個類型組合成一個單一類型,創(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 data8.映射類型
映射類型允許我們通過轉(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
裝飾器允許我們修改或擴展類、方法、屬性和其他聲明的行為。
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.索引簽名
索引簽名允許我們在接口或類型中定義動態(tài)屬性名稱及其對應的類型。
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可以根據(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.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.類型別名
類型別名允許我們?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)與類
類型保護也可以與類一起使用,以縮小對象實例的類型范圍。
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)文章
js行號顯示的文本框?qū)崿F(xiàn)效果(兼容多種瀏覽器 )
本文主要介紹了javascript實現(xiàn)行號顯示的文本框效果,這樣就可以解決讀者很難迅速找到所在某一行的對應代碼,感興趣的小伙伴們可以參考一下2015-10-10
讓html元素隨瀏覽器的大小自適應垂直居中的實現(xiàn)方法
下面小編就為大家?guī)硪黄宧tml元素隨瀏覽器的大小自適應垂直居中的實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10
DOM_window對象屬性之--clipboardData對象操作代碼
clipboardData 對象提供了對于預定義的剪貼板格式的訪問,以便在編輯操作中使用。2011-02-02
微信小程序?qū)崿F(xiàn)限制用戶轉(zhuǎn)發(fā)功能的實例代碼
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)限制用戶轉(zhuǎn)發(fā)的實例代碼,通過截圖加實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02
Three.js利用Detector.js插件如何實現(xiàn)兼容性檢測詳解
這篇文章主要給大家介紹了關(guān)于Three.js利用Detector.js插件如何實現(xiàn)兼容性檢測的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起看看吧。2017-09-09

