MST
星途 面试题库

面试题:TypeScript数组类型在复杂场景下的应用

假设有一个场景,需要处理多层嵌套的数组结构,其中最内层数组元素是不同类型(比如string、number、boolean),但每一层外层数组的元素类型必须相同。请用TypeScript定义合适的类型,并编写一个函数,该函数可以遍历这个多层嵌套数组,将所有string类型的元素转换为大写并返回一个新的多层嵌套数组结构,保持原有的嵌套层次。
11.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义递归类型来表示多层嵌套数组
type NestedArray<T> = (NestedArray<T> | T)[];

function transformNestedArray(arr: NestedArray<string | number | boolean>): NestedArray<string | number | boolean> {
    return arr.map((item) => {
        if (Array.isArray(item)) {
            return transformNestedArray(item);
        } else if (typeof item ==='string') {
            return item.toUpperCase();
        }
        return item;
    });
}