簡體   English   中英

如何在 typescript 中將任意數組轉換為包含其他數據類型的字符串數組?

[英]How do I convert an any array to a string array containing other datatypes inside in typescript?

我正在做一個 typescript 教程練習,希望我將任何 [] 數組更改為字符串 []。

// 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)
    }
    }

上面的一個有效,但是如果我將任何[]更改為字符串[],它就不起作用。 如果我做

"const manufacturers: [string,boolean][]="然后它識別 boolean 而不是字符串。 我試圖理解為什么它不將 id 視為字符串變量並使其匹配。 如何在不使用“任何 []”的情況下完成此操作

manufacturers的類型是{ id: string, checked: boolean }[]

解釋:

manufacturers object 是一個數組,包含對象。 每個 object 都有一個id和一個checked屬性,它們分別是 string 和 boolean 類型。

正如您所說,從any[]更改為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM