简体   繁体   English

如何在 typescript 中将任意数组转换为包含其他数据类型的字符串数组?

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

I'm doing a typescript tutorial exercise that wants me to change an any[] array into string[].我正在做一个 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)
    }
    }

The above one works, but if I change any[] into string[], it doesn't work.上面的一个有效,但是如果我将任何[]更改为字符串[],它就不起作用。 If I do如果我做

"const manufacturers: [string,boolean][]=" then it recognizes the boolean and not the string. "const manufacturers: [string,boolean][]="然后它识别 boolean 而不是字符串。 I'm trying to understand why it doesn't see id as a string variable and make it match.我试图理解为什么它不将 id 视为字符串变量并使其匹配。 How do I accomplish this without using 'any[]'如何在不使用“任何 []”的情况下完成此操作

The type of manufacturers is { id: string, checked: boolean }[] . manufacturers的类型是{ id: string, checked: boolean }[]

Explanation:解释:

The manufacturers object is an array, containing objects. manufacturers object 是一个数组,包含对象。 Each object has an id and a checked property which are of types string and boolean respectively.每个 object 都有一个id和一个checked属性,它们分别是 string 和 boolean 类型。

So as you said, changing from any[] to string[] won't work, because the manufacturers type is not string[] , but { id: string, checked: 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)
  }
}

As @Calz pointed out, you don't need to explicitly enter the type of the variable, as initialization is taking place at the time of declaration.正如@Calz 指出的那样,您不需要显式输入变量的类型,因为初始化是在声明时进行的。

Here's a small example explaining this:这是一个解释这一点的小例子:

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