考虑以下接口

type State = {
  data: any[]
  index: number
  size: number
  count: number
  loading: boolean
  error: string | undefined
}

我需要创建一个类型,该类型是其属性的并集

{data: any[]} | {index: number} | {size: number} |...

到目前为止,我能够通过使用索引类型访问来合并所有返回类型,但我将获得接口属性的返回类型的并集.

推荐答案

您需要使用distributive-conditional-types:

type State = {
    data: any[]
    index: number
    size: number
    count: number
    loading: boolean
    error: string | undefined
}

type Split<T> = keyof T extends infer Keys // turn on distributivity
    ? (Keys extends PropertyKey
        ? (Keys extends keyof T
            ? Record<Keys, T[Keys]> // apply to each key, or { [prop in Keys]: T[Keys] }for readability
            : never)
        : never)
    : never

//  Record<"data", any[]> | Record<"index", number> | Record<"size", number> ...
type Result = Split<State>

Playground

Typescript相关问答推荐

类型保护,用于验证是否定义了二元组的每个项

为什么在将条件返回类型的字符串赋给数字时没有类型错误?

类型脚本如何将嵌套的通用类型展开为父通用类型

当类型断言函数返回假时,TypScript正在推断从不类型

如何缩小变量访问的对象属性范围?

如何键入函数以只接受映射到其他一些特定类型的参数类型?

为什么有条件渲染会导致material 自动完成中出现奇怪的动画?

ANGLE独立组件布线错误:没有ActivatedRouting提供程序

如何从扩展接口推断泛型?

类型TTextKey不能用于索引类型 ;TOption

是否将自动导入样式从`~/目录/文件`改为`@/目录/文件`?

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

类型脚本可以推断哪个类型作为参数传递到联合类型中吗?

通过泛型函数本身推断受约束的泛型参数的类型脚本问题

如何从MAT-FORM-FIELD-MAT-SELECT中移除焦点?

如何在脚本中输入具有不同数量的泛型类型变量的函数?

界面中数组中的混合类型导致打字错误

TypeScrip:使用Cypress测试包含插槽的Vue3组件

获取类属性的类型';TypeScript中的getter/setter

在Vite中将SVG导入为ReactComponent-不明确的间接导出:ReactComponent