面试题答案
一键面试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));
上述代码解释:
- 首先使用
Partial
工具类型将Employee
接口及其嵌套的所有属性变为可选,得到OptionalEmployee
类型。 - 定义
getSetProperties
函数,通过递归的方式检查对象中设置了值的属性路径,并返回这些路径组成的数组。 - 最后创建一个
OptionalEmployee
类型的对象并调用getSetProperties
函数进行测试。