MST
星途 面试题库

面试题:TypeScript中Record工具类型在复杂数据结构中的深度应用

现有一个复杂的数据结构,外层是一个对象,键是部门名称(字符串类型),值是另一个对象,这个内部对象的键是员工ID(数字类型),值是员工信息对象,员工信息对象有 `name`(字符串类型)、`age`(数字类型)、`role`(字符串类型)字段。请使用Record工具类型定义这个复杂数据结构的类型。然后编写一个函数,接收这个复杂数据结构和一个部门名称作为参数,返回该部门中年龄大于30岁且 `role` 为 `'manager'` 的员工数量。
49.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 使用Record工具类型定义复杂数据结构的类型
type EmployeeInfo = {
    name: string;
    age: number;
    role: string;
};
type DepartmentEmployees = Record<number, EmployeeInfo>;
type CompanyStructure = Record<string, DepartmentEmployees>;

// 编写函数
function countEligibleEmployees(structure: CompanyStructure, departmentName: string): number {
    const department = structure[departmentName];
    if (!department) {
        return 0;
    }
    return Object.values(department).filter(employee => employee.age > 30 && employee.role ==='manager').length;
}