如何将字符串数组string[]
映射到带有字符串[string, string]
的二维数组?
我尝试过
const animals: string[] = ['Dog', 'Cat', 'Mouse'];
// This throws an error
let splittedArray: [string, string] = animals.slice(0,2);
// This doesn't throw an error
// let splittedArray: [string, string] = ['Dog', 'Cat'];
// Error Message
// Type 'string[]' is missing the following properties from type '[string, string]': 0, 1 ts(2739)
我想要的输出应该是:
console.log(splittedArray);
// ['Dog', 'Cat']
答案 0 :(得分:1)
您要2D数组还是2个元素的数组?这似乎适合您的输出:
const animals: string[] = ['Dog', 'Cat', 'Mouse'];
let splittedArray: string[] = animals.slice(0,2);
答案 1 :(得分:1)
只需将类型声明更改为此... as
运算符主要是为*.tsx
文件设计的,以避免语法不明确。工作StackBlitz Link is
const animals: string[] = ['Dog', 'Cat', 'Mouse'];
let splittedArray = animals.slice(0,2) as [string,string];
console.log(splittedArray)