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

如何在TypeScript中获取按父类型区分的联合类型键数组

如何获取按父类型区分的联合类型键数组?

要实现你需要的按父实体类型区分的键数组联合类型,可以使用映射类型 + 索引访问的组合写法:

type userType = {
    userId: number
    name: string
}

type postType = {
    postId: number,
    title: string
}

type entityTypes = {
    user: userType,
    post: postType
}

// 正确的类型定义
type entityFieldsArray = {
  [K in keyof entityTypes]: (keyof entityTypes[K])[]
}[keyof entityTypes];

这个写法的逻辑是:

  1. 通过映射类型遍历entityTypes的每一个键K(也就是user和post)
  2. 对每个K,生成对应子类型entityTypes[K]的键组成的数组类型,比如user对应(keyof userType)[]即("userId" | "name")[]
  3. 最后通过[keyof entityTypes]索引访问映射后的类型,得到所有子类型键数组的联合类型,正好是你需要的("userId" | "name")[] | ("postId" | "title")[]

分析你之前的写法问题

  • 第一种写法keyof prismaIncludes_t[keyof prismaIncludes_t]返回never:因为prismaIncludes_t[keyof prismaIncludes_t]是userType | postType联合类型,而keyof作用于联合类型时,只有当所有联合成员有共同的键名时才会返回对应键,否则结果就是never,这里两个子类型没有共同键,所以得到never。
  • 第二种写法得到混合键数组:KeysOfUnion<entityTypes[keyof entityTypes]>会把联合类型中每个成员的键合并成一个大的联合("userId" | "name" | "postId" | "title"),再套数组自然就是混合的键数组,不符合按父类型区分的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:15:29