考慮以下 TypeScript 代碼片段:
function processInput(input: string | number): void {
if (typeof input === "string") {
console.log(`Input is a string: ${input.toUpperCase()}`);
} else if (typeof input === "number") {
console.log(`Input is a number: ${input.toFixed(2)}`);
}
}
const example1: string | number = "Hello";
const example2: string | number = 42;
processInput(example1);
processInput(example2);
1、請解釋 processInput 函數(shù)的作用和輸入?yún)?shù)的類型。
2、解釋變量 example1 和 example2 的類型注解。
3、描述 TypeScript 在調(diào)用 processInput(example1) 和 processInput(example2) 時是如何進行類型推導(dǎo)的。
解答:
1、processInput 函數(shù)接受一個參數(shù) input,該參數(shù)的類型是 string 或 number。函數(shù)根據(jù)輸入?yún)?shù)的實際類型,在控制臺輸出不同的信息。如果 input 是字符串,則輸出其大寫形式;如果是數(shù)字,則輸出其保留兩位小數(shù)的形式。
2、example1 和 example2 的類型注解分別是 string | number,表示這兩個變量可以是字符串或數(shù)字類型的值。文章來源:http://www.zghlxwxcb.cn/news/detail-810628.html
3、在調(diào)用 processInput(example1) 時,TypeScript 推導(dǎo)出 example1 是字符串類型,因為它在聲明時被賦值為字符串。在調(diào)用 processInput(example2) 時,TypeScript 推導(dǎo)出 example2 是數(shù)字類型,因為它在聲明時被賦值為數(shù)字。這種類型推導(dǎo)使得函數(shù)在運行時能夠正確地處理不同類型的輸入?yún)?shù)。文章來源地址http://www.zghlxwxcb.cn/news/detail-810628.html
到了這里,關(guān)于Typescript的類型推導(dǎo)與聯(lián)合類型的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!