MST

星途 面试题库

面试题:TypeScript可选与剩余参数在复杂场景的应用

假设你正在开发一个前端数据处理模块,有一个函数需要处理用户输入数据。该函数接受一个基础数据对象(必选),一个可选的过滤条件对象(包含字符串或数字类型属性),以及一些额外的操作指令作为剩余参数(字符串类型)。要求使用TypeScript定义合适的类型,并实现该函数,使其能根据过滤条件筛选基础数据对象的属性,并按照操作指令对筛选后的数据进行简单操作(如排序,反转等),最后返回处理结果。
34.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 定义过滤条件对象的类型
type FilterCondition = {
    [key: string]: string | number;
};

// 定义操作指令类型
type Operation = 'sort' | 'reverse';

// 定义函数参数类型
type DataProcessorParams = [Record<string, any>, FilterCondition?, ...Operation[]];

// 实现数据处理函数
function dataProcessor(...args: DataProcessorParams): Record<string, any> {
    const [baseData, filterCondition = {}, ...operations] = args;
    let result: Record<string, any> = {};

    // 根据过滤条件筛选属性
    for (const key in baseData) {
        if (Object.prototype.hasOwnProperty.call(baseData, key) && (filterCondition[key] === undefined || baseData[key] === filterCondition[key])) {
            result[key] = baseData[key];
        }
    }

    // 按照操作指令进行操作
    operations.forEach(operation => {
        if (operation === 'sort') {
            const keys = Object.keys(result).sort();
            result = keys.reduce((acc, key) => {
                acc[key] = result[key];
                return acc;
            }, {} as Record<string, any>);
        } else if (operation === 'reverse') {
            const keys = Object.keys(result).reverse();
            result = keys.reduce((acc, key) => {
                acc[key] = result[key];
                return acc;
            }, {} as Record<string, any>);
        }
    });

    return result;
}