MST

星途 面试题库

面试题:TypeScript 中 Partial 和 Readonly 结合复杂类型的应用

假设有一个复杂类型,如下:interface User { profile: { name: string; address: { city: string; country: string }; hobbies: string[]; }; settings: { theme: 'light' | 'dark'; notifications: boolean; }; } 请编写一个函数,该函数接收一个 User 类型的对象,使用 Partial 和 Readonly 映射类型,将传入对象的 'profile' 部分变为可选且只读,'settings' 部分保持不变,然后返回这个新的对象结构,并解释为什么这样做以及这样做在实际项目中的应用场景。
17.4万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
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
    };
}

解释

  1. 使用 Partial 映射类型将 profile 变为可选,Partial<Type> 会将 Type 中的所有属性变为可选。这里 profile 本身是一个对象,所以使用 ? 来表示其可选性。
  2. 使用 Readonly 映射类型将 profile 变为只读,Readonly<Type> 会将 Type 中的所有属性变为只读。这里通过 Object.freeze(user.profile) 来实现对 profile 对象的只读转换,Object.freeze 会冻结一个对象,使其不能被修改。
  3. 保持 settings 部分不变,直接返回 user.settings

应用场景

  1. 数据传递与保护:在实际项目中,当需要将用户数据传递到其他模块,而又不希望该模块意外修改用户的 profile 信息时,将 profile 设为只读可以提供数据保护。同时,profile 变为可选,可能用于一些情况下,某些操作并不依赖用户的 profile 信息,使得函数或模块的使用更加灵活。
  2. API 响应处理:当从 API 获取用户数据后,将 profile 部分设为只读且可选,防止在本地对 profile 数据进行误操作修改,并且在不需要 profile 数据时,不会因为缺少该字段而报错。