首页 > 解决方案 > 打字稿:将字符串 [] 映射到 [字符串,字符串]

问题描述

如何将字符串数组映射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']

标签: angulartypescript

解决方案


你想要一个二维数组还是一个有 2 个元素的数组?这似乎适用于您的输出:

    const animals: string[] = ['Dog', 'Cat', 'Mouse'];
    let splittedArray: string[] = animals.slice(0,2);

推荐阅读