15個(gè)用于開發(fā)的TypeScript高級(jí)技巧分享
1.可選鏈 (?.)
可選鏈允許你安全地訪問嵌套屬性或方法,無需擔(dān)心 null 或 undefined 值。如果任何中間屬性為 null 或 undefined,它會(huì)立即終止評(píng)估。
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.空值合并運(yùn)算符 (??)
空值合并運(yùn)算符在變量為 null 或 undefined 時(shí)提供默認(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無法推斷變量類型時(shí),顯式地定義變量的類型。
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 運(yùn)算符
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.147.交叉類型
交叉類型允許我們將多個(gè)類型組合成一個(gè)單一類型,創(chuàng)建一個(gè)新類型,該類型具有交叉類型的所有屬性和方法。
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
裝飾器允許我們修改或擴(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 DOE11.索引簽名
索引簽名允許我們?cè)诮涌诨蝾愋椭卸x動(dòng)態(tài)屬性名稱及其對(duì)應(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: undefined12. 條件語句中的類型推斷
TypeScript可以根據(jù)條件語句推斷類型,從而使代碼更加簡(jiǎn)潔。
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)與類
類型保護(hù)也可以與類一起使用,以縮小對(duì)象實(shí)例的類型范圍。
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個(gè)用于開發(fā)的TypeScript高級(jí)技巧分享的文章就介紹到這了,更多相關(guān)TypeScript技巧內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
js行號(hào)顯示的文本框?qū)崿F(xiàn)效果(兼容多種瀏覽器 )
本文主要介紹了javascript實(shí)現(xiàn)行號(hào)顯示的文本框效果,這樣就可以解決讀者很難迅速找到所在某一行的對(duì)應(yīng)代碼,感興趣的小伙伴們可以參考一下2015-10-10
讓html元素隨瀏覽器的大小自適應(yīng)垂直居中的實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄宧tml元素隨瀏覽器的大小自適應(yīng)垂直居中的實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-10-10
DOM_window對(duì)象屬性之--clipboardData對(duì)象操作代碼
clipboardData 對(duì)象提供了對(duì)于預(yù)定義的剪貼板格式的訪問,以便在編輯操作中使用。2011-02-02
js點(diǎn)擊頁(yè)面其它地方將某個(gè)顯示的DIV隱藏
今天一朋友問我 點(diǎn)擊一按鈕彈出一個(gè)DIV,然后要求點(diǎn)擊頁(yè)面其它地方隱藏這個(gè)DIV2012-07-07
uni-app入門頁(yè)面布局之window和tabbar詳解
每個(gè)頁(yè)面按照結(jié)構(gòu)可以分成三部分:window?page?tabbar.其中window和tabbar一般比較固定,page是平常業(yè)務(wù)開展的主要載體,根據(jù)業(yè)務(wù)需求進(jìn)行頁(yè)面配置。下面主要講一下window和tabbar,感興趣的朋友跟隨小編一起看看吧2022-11-11
微信小程序?qū)崿F(xiàn)限制用戶轉(zhuǎn)發(fā)功能的實(shí)例代碼
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)限制用戶轉(zhuǎn)發(fā)的實(shí)例代碼,通過截圖加實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02
Three.js利用Detector.js插件如何實(shí)現(xiàn)兼容性檢測(cè)詳解
這篇文章主要給大家介紹了關(guān)于Three.js利用Detector.js插件如何實(shí)現(xiàn)兼容性檢測(cè)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。2017-09-09

