TypeScript 数组、元组、枚举及对象的高效使用
在编程实践中,TypeScript 提供了一系列强大的特性,帮助开发者更高效地处理数组、元组、枚举和对象。下面将详细介绍这些特性的使用方法和优势。
模板字面量字符串类型的运用
在某些情况下,我们可能需要创建只接受特定值的模板字符串。TypeScript 的字面量字符串类型可以与 JavaScript 的模板字符串特性结合使用,实现这一需求。以下是一个示例代码:
function calculatePrice(quantity: 1 | 2, price: number): number {
return quantity * price;
}
let total = calculatePrice(2, 19.99);
console.log(`Price: ${total}`);
function getRandomValue(): 1 | 2 | 3 | 4 {
return Math.floor(Math.random() * 4) + 1 as 1 | 2 | 3 | 4;
}
function getCityString(city: "London" | "Paris" | "Chicago")
: `City: ${"London" | "Paris" | "Chicago"}` {
return `City: ${city}` as `City: ${"London" | "Paris" | "Chicago"}`;
}
let str = getCityString("London");
conso
超级会员免费看
订阅专栏 解锁全文
1451

被折叠的 条评论
为什么被折叠?



