Typescript 中的复杂类型解析

Complex type resolution in Typescript

我的 Typescript 中定义了一个非常复杂的类型:

export type DraftCamp = DeepPartial<CampForm> & {
  isActive: false
} & FilesExtension

这实际上只是一个带有一些嵌套值的接口——没有联合。有没有办法看一看这种类型,看看它到底是什么样子的?我可以在不手动关注它引用的所有其他类型的情况下执行此操作吗?

您可以使用映射到交叉点上的 Id 类型。无法保证什么会扩展映射类型,但这种类型目前可以解决问题:

type Id<T> = {} & {
  [P in keyof T]: Id<T[P]>
}

在十字路口使用 Id 会使它变平:

type FilesExtension = {
  ext: string
}

// Naive implementation, just filler
type DeepPartial<T> = {
  [P in keyof T]?: DeepPartial<T[P]>
}

type CampForm = {
  foo: {
    bar: string
  }
  baz: {
    bars: string[]
  }
}

type Id<T> = {} & {
  [P in keyof T]: Id<T[P]>
}
export type DraftCamp = Id<DeepPartial<CampForm> & {
  isActive: false
} & FilesExtension>
// Hover over DraftCamp and you will see the expanded version of it:
// type DraftCamp = {
//     foo?: {
//         bar?: string | undefined;
//     } | undefined;
//     baz?: {
//         bars?: (string | undefined)[] | undefined;
//     } | undefined;
//     isActive: false;
//     ext: string;
// }

Playground Link

注意:我必须警告你,在交集和具有相同成员的扁平化类型之间有一些神秘的可分配性规则不同,但它的工作原理基本相同。这个想法是 Id 很像 console.log 对调试很有用,但不要让它留在生产代码中