You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免TypeScript嵌套Pick类型中的属性名拼写错误?

让TypeScript检测嵌套对象属性拼写错误的方案

我们定义了两个接口用于描述文件和用户数据:

interface DownloadFile {
  id: string
  name: string
  user: User
  createdAt: Date
}

interface User {
  id: string
  name: string
  isEmailValidated: boolean
  unsubscribe: boolean
  email: string
}

当前通过Pick和交叉类型可以筛选所需数据,但如果嵌套属性名拼写错误(比如把user写成userTYPO),TypeScript不会抛出错误。以下是几种解决方法:

方法一:用Omit替代Pick做属性约束

Omit会排除原接口中指定的属性,剩下的属性严格匹配原接口结构,新增不存在的属性会直接报错:

type QueryResponse = {
  file: Omit<DownloadFile, 'createdAt'> & {
    user: Pick<User, 'id' | 'name' | 'email'>
  }
}

如果把user写成userTYPO,TypeScript会提示该属性不属于DownloadFile类型。

方法二:利用satisfies运算符做类型校验(TypeScript 4.9+)

通过satisfies强制QueryResponse的file属性只能包含DownloadFile中的字段:

type QueryResponse = {
  file: Pick<DownloadFile, 'id' | 'name'> & {
    user: Pick<User, 'id' | 'name' | 'email'>
  }
} satisfies {
  file: Partial<DownloadFile>
}

拼写错误时,satisfies会检测到file包含未定义的属性,触发类型错误。

方法三:映射类型精确控制嵌套属性

通过映射类型遍历原接口的属性,只保留需要的字段并自定义嵌套属性结构,完全约束属性名:

type QueryResponse = {
  file: {
    [K in keyof DownloadFile as K extends 'createdAt' ? never : K]: 
      K extends 'user' ? Pick<User, 'id' | 'name' | 'email'> : DownloadFile[K]
  }
}

这种方式既保留原接口的属性名限制,又能自定义user的子属性,任何拼写错误都会被TypeScript立即识别。

内容的提问来源于stack exchange,提问作者Alan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:36:23