【问题标题】:Complex type resolution in TypescriptTypescript 中的复杂类型解析
【发布时间】:2020-04-10 17:10:59
【问题描述】:

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

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

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

【问题讨论】:

  • 您的意思是扩展类型以查看所有成员?
  • 完全是这样的
  • 嗯,下面有好消息????

标签: typescript types interface alias


【解决方案1】:

您可以使用映射交叉路口的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 对调试很有用,但不要把它留在生产代码中

【讨论】:

  • 太酷了 :) 我在使用 Intellij 时遇到了问题 - 当我想在 Intellij 中查看它的扩展版本时,使用它的功能“类型信息”(ctrl + shift + p ) 它不会扩展嵌套字段。
  • 另外,有没有办法将这样的扩展名转储到文本文件中,即。用于文档目的?
  • @Hyster 无法将其转储到文件中,我通常使用 VSCode 或操场,在那里你可以在工具提示中获得完整的扩展版本,你可以从那里复制它..如果你是够快:)
猜你喜欢
  • 2017-10-21
  • 2019-07-11
  • 2021-04-19
  • 2020-03-04
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
相关资源
最近更新 更多