MST

星途 面试题库

面试题:TypeScript 可选参数在复杂业务场景下的优化

假设你正在开发一个前端项目,有一个功能是根据用户选择的不同条件进行数据筛选和展示。这些条件通过一个函数的参数传递,其中部分条件是可选的。在这个复杂业务场景下,如何设计函数的可选参数,以提高代码的可维护性和性能?请结合实际项目经验,分析可能遇到的类型相关问题及解决方案。
35.1万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

设计函数可选参数以提高可维护性和性能

  1. 对象解构方式定义可选参数
    • 在JavaScript中,使用对象解构来定义可选参数是一种很好的方式。例如:
    function filterData({ condition1 = 'defaultValue1', condition2 = 'defaultValue2' } = {}) {
        // 函数逻辑,根据condition1和condition2进行数据筛选
    }
    
    • 这样做的好处是,函数调用者可以只传入他们关心的参数,而不必按照固定顺序传入所有参数。而且,如果未来需要添加新的可选参数,不会影响现有调用者的代码。
  2. 默认参数值
    • 为每个可选参数设置合理的默认值。这有助于在调用者未提供参数时,函数仍能正常工作。例如,在上述代码中,condition1condition2都有默认值。
  3. 性能方面
    • 对于频繁调用的函数,减少不必要的计算。可以在函数内部对参数进行缓存,如果参数值未改变,直接使用缓存结果。例如:
    let cache = {};
    function filterData({ condition1 = 'defaultValue1', condition2 = 'defaultValue2' } = {}) {
        const key = `${condition1}-${condition2}`;
        if (cache[key]) {
            return cache[key];
        }
        // 实际的数据筛选逻辑
        const result = performFilter(condition1, condition2);
        cache[key] = result;
        return result;
    }
    

可能遇到的类型相关问题及解决方案

  1. 参数类型不匹配
    • 问题:调用者传入的参数类型与函数预期不符,比如期望一个字符串类型的condition1,但传入了数字。
    • 解决方案
      • 使用类型检查库,如TypeScript。在TypeScript中,可以这样定义函数:
      function filterData({ condition1 = 'defaultValue1', condition2 = 'defaultValue2' }: { condition1?: string; condition2?: string } = {}): void {
          // 函数逻辑
      }
      
      • 如果使用JavaScript,可以手动进行类型检查。例如:
      function filterData({ condition1 = 'defaultValue1', condition2 = 'defaultValue2' } = {}) {
          if (typeof condition1!=='string') {
              throw new Error('condition1 should be a string');
          }
          if (typeof condition2!=='string') {
              throw new Error('condition2 should be a string');
          }
          // 函数逻辑
      }
      
  2. 复杂对象类型问题
    • 问题:当可选参数是复杂对象时,可能难以确保对象结构的正确性。比如,期望对象有特定的属性和类型,但传入的对象不符合要求。
    • 解决方案
      • 在TypeScript中,可以定义接口来明确对象结构。例如:
      interface FilterOptions {
          condition1?: string;
          condition2?: string;
          subObject?: {
              subProperty1: number;
              subProperty2: boolean;
          };
      }
      function filterData(options: FilterOptions = {}): void {
          // 函数逻辑
      }
      
      • 在JavaScript中,可以通过递归检查对象结构和类型来确保正确性。例如:
      function validateSubObject(obj) {
          return typeof obj === 'object' && 'subProperty1' in obj && typeof obj.subProperty1 === 'number' &&'subProperty2' in obj && typeof obj.subProperty2 === 'boolean';
      }
      function filterData({ condition1 = 'defaultValue1', condition2 = 'defaultValue2', subObject } = {}) {
          if (subObject &&!validateSubObject(subObject)) {
              throw new Error('subObject has incorrect structure');
          }
          // 函数逻辑
      }