MST

星途 面试题库

面试题:TypeScript中Partial工具类型在复杂对象结构中的应用

已知有一个多层嵌套的接口结构:interface Address { street: string; city: string; } interface Company { name: string; address: Address; } interface Employee { name: string; age: number; company: Company; }。请使用Partial工具类型创建一个新类型,使得Employee接口及其嵌套的所有属性都变为可选。然后编写一个函数,该函数接收这个新类型的参数,递归检查并返回所有设置了值的属性路径(例如:['name', 'company', 'address','street'])。
38.5万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
interface Address {
    street: string;
    city: string;
}

interface Company {
    name: string;
    address: Address;
}

interface Employee {
    name: string;
    age: number;
    company: Company;
}

// 使用Partial工具类型创建新类型
type OptionalEmployee = Partial<Employee>;

function getSetProperties<T>(obj: T, path: string[] = []): string[][] {
    let result: string[][] = [];
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            const value = (obj as any)[key];
            if (value!== undefined) {
                if (typeof value === 'object' && value!== null) {
                    result = result.concat(getSetProperties(value, [...path, key]));
                } else {
                    result.push([...path, key]);
                }
            }
        }
    }
    return result;
}

// 测试
const optionalEmployee: OptionalEmployee = {
    name: 'John',
    age: 30,
    company: {
        name: 'ABC Company',
        address: {
            street: '123 Main St',
            city: 'Anytown'
        }
    }
};

console.log(getSetProperties(optionalEmployee));

上述代码解释:

  1. 首先使用Partial工具类型将Employee接口及其嵌套的所有属性变为可选,得到OptionalEmployee类型。
  2. 定义getSetProperties函数,通过递归的方式检查对象中设置了值的属性路径,并返回这些路径组成的数组。
  3. 最后创建一个OptionalEmployee类型的对象并调用getSetProperties函数进行测试。