Typescript - Type alias 'T' circularly references itself?

type Children<T> = { children: Record<string, T> }

type TPartial = { info: string }

// Error: Type alias 'TRequired' circularly references itself.
type TRequired = { id: string } & Children<T>

// Error: Type alias 'T' circularly references itself.
type T = Partial<TPartial> & AtLeastOne<TRequired>

// 至少包含一个属性
type AtLeastOne<T, K extends keyof T = keyof T> = K extends unknown
    ? Pick<T, K> & Partial<Omit<T, K>>
    : never;

但是这样写就没有问题:

type TPartial = { info: string }

type TRequired = { id: string } & { children: Record<string, T> }

type T = Partial<TPartial> & AtLeastOne<TRequired>

type Children 是一个通用的工具类型,但是有些地方可以写,有些地方就会报循环引用。如果我有些地方写 Children 有些地方写 { children: T } 那还不如不要这个类型。有没有类型体操高手救救我?

阅读 2.6k
1 个回答
type TPartial = { info: string };

type AtLeastOne<T, K extends keyof T = keyof T> = K extends unknown
  ? Pick<T, K> & Partial<Omit<T, K>>
  : never;

type TRequired<T = unknown> = { id: string } & { children: Record<string, T> };

type T = Partial<TPartial> & AtLeastOne<TRequired>;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏