面试题答案
一键面试interface User {
profile: {
name: string;
address: {
city: string;
country: string;
};
hobbies: string[];
};
settings: {
theme: 'light' | 'dark';
notifications: boolean;
};
}
function transformUser(user: User): {
profile?: Readonly<User['profile']>;
settings: User['settings'];
} {
return {
profile: user.profile? Object.freeze(user.profile) : undefined,
settings: user.settings
};
}
解释:
- 使用
Partial
映射类型将profile
变为可选,Partial<Type>
会将Type
中的所有属性变为可选。这里profile
本身是一个对象,所以使用?
来表示其可选性。 - 使用
Readonly
映射类型将profile
变为只读,Readonly<Type>
会将Type
中的所有属性变为只读。这里通过Object.freeze(user.profile)
来实现对profile
对象的只读转换,Object.freeze
会冻结一个对象,使其不能被修改。 - 保持
settings
部分不变,直接返回user.settings
。
应用场景:
- 数据传递与保护:在实际项目中,当需要将用户数据传递到其他模块,而又不希望该模块意外修改用户的
profile
信息时,将profile
设为只读可以提供数据保护。同时,profile
变为可选,可能用于一些情况下,某些操作并不依赖用户的profile
信息,使得函数或模块的使用更加灵活。 - API 响应处理:当从 API 获取用户数据后,将
profile
部分设为只读且可选,防止在本地对profile
数据进行误操作修改,并且在不需要profile
数据时,不会因为缺少该字段而报错。