MST

星途 面试题库

面试题:TypeScript类型推断与类型注解在复杂数据结构中的应用

假设有一个包含嵌套数组和对象的复杂数据结构,例如:`const data = [ { name: 'Alice', scores: [85, 90, 78] }, { name: 'Bob', scores: [70, 65, 80] } ];`。请编写一个函数,接受这个数据结构作为参数,计算每个学生的平均分数并返回。在编写过程中,充分利用TypeScript的类型推断和类型注解,确保代码的类型安全,并解释在这个场景下类型推断与类型注解各自起到的作用。
42.0万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
interface Student {
    name: string;
    scores: number[];
}

function calculateAverageScores(data: Student[]): { [name: string]: number } {
    const result: { [name: string]: number } = {};
    for (const student of data) {
        const total = student.scores.reduce((acc, score) => acc + score, 0);
        result[student.name] = total / student.scores.length;
    }
    return result;
}

// 示例使用
const data: Student[] = [
    { name: 'Alice', scores: [85, 90, 78] },
    { name: 'Bob', scores: [70, 65, 80] }
];
const averageScores = calculateAverageScores(data);
console.log(averageScores);

类型推断与类型注解的作用解释:

  1. 类型推断
    • calculateAverageScores 函数内部,TypeScript 可以根据 student.scores.reduce 表达式推断出 total 的类型为 number,因为 student.scoresnumber[] 类型,reduce 方法返回的结果类型基于数组元素类型进行推断。
    • 同样,student.scores.lengthnumber 类型,所以 total / student.scores.length 的结果类型也被推断为 number,进而 result[student.name] 的类型也被推断为 number
  2. 类型注解
    • 定义 Student 接口时,明确了 namestring 类型,scoresnumber[] 类型。这使得代码阅读者和编辑器能清晰了解数据结构的组成。
    • calculateAverageScores 函数参数 data 上使用 Student[] 类型注解,确保传入的参数是符合 Student 接口的数组,提供了类型安全保障。
    • 函数返回值类型 { [name: string]: number } 使用类型注解,明确告知调用者该函数返回一个对象,对象的键是字符串(学生名字),值是数字(平均分数),增强了代码的可读性和可维护性。