我正在做一個打字稿教程練習,希望我將 any[] 陣列更改為 string[]。
// declaring an array of any datatype
const manufacturers: any[] = [{ id: 'Samsung', checked: false },
{ id: 'Motorola', checked: false },
{ id: 'Apple', checked: false },
{ id: 'Sony', checked: false }
];
console.log('Available Products are: ');
// logic to populate the above declared array's id value
for (const item of manufacturers) {
console.log(item.id);
if(item.id === "Apple")
{
console.log("check value is " item.checked)
}
}
上面的一個有效,但如果我將 any[] 更改為 string[],則無效。如果我做
"const manufacturers: [string,boolean][]="
然后它識別布林值而不是字串。我試圖理解為什么它沒有將 id 視為字串變數并使其匹配。如何在不使用“any[]”的情況下完成此操作
uj5u.com熱心網友回復:
的型別manufacturers是{ id: string, checked: boolean }[]。
解釋:
該manufacturers物件是一個陣列,包含物件。每個物件都有一個id和一個checked屬性,分別是字串和布爾型別。
所以正如你所說,從any[]to改變是string[]行不通的,因為manufacturers型別不是string[],而是{ id: string, checked: boolean }[]。
const manufacturers: { id: string, checked: boolean }[] = [{ id: 'Samsung', checked: false },
{ id: 'Motorola', checked: false },
{ id: 'Apple', checked: false },
{ id: 'Sony', checked: false }
];
console.log('Available Products are: ');
for (const item of manufacturers) {
console.log(item.id);
if (item.id === "Apple") {
console.log("check value is " item.checked)
}
}
正如@Calz 指出的那樣,您不需要顯式輸入變數的型別,因為初始化是在宣告時進行的。
這是一個解釋這一點的小例子:
let a;
a = 5
console.log(typeof a) // number
a = "string"
console.log(typeof a) // string
let b = 5
b = "some string"; // error as TypeScript blames that type string is not assignable to type number
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/388754.html
標籤:javascript 数组 细绳 打字稿 任何
