从推断的 TypeScript 接口生成显式接口代码

Generate Explicit Interface code from Inferred TypeScript Interface

比方说,我有一个代码片段:

const todo = {name: "Learn Some TS", isDone: true}

如何自动生成以下内容:

interface TodoInterface {
    name: string
    isDone: Boolean
}

寻找可以从代码片段获取界面的任何工具。它不一定必须解决这个确切的场景。

在我使用的 IDE 中(VSCode 和 The TypeScript Playground), I hover the pointer over the value whose type I want to capture. This brings up IntelliSense quick info 描述类型,您可以复制并粘贴它。

对于

const todo = { name: "Learn Some TS", isDone: true }

提供的信息如下所示

/* const todo: {
    name: string;
    isDone: boolean;
} */

可以复制、粘贴和修改给你

interface TodoInterface {
  name: string;
  isDone: boolean;
}

补充屏幕截图演示:


请注意,您的编译器选项可能最终会截断 long 类型。例如,假设您有这种类型:

type SomeFiltered<T extends any[]> =
  T extends [infer F, ...infer R] ? [F, ...SomeFiltered<R>] | SomeFiltered<R> : []

它需要 tuple type and produces a union 所有可能的过滤版本。由于每个元素可以存在或不存在,因此您最终将一个元素元组转换为 2 个元组的并集。好多啊。所以这个

type LongType = SomeFiltered<["A", "B", "C", "D", "E"]>

预计有32个工会成员。使用默认编译器选项,您将看不到带有 IntelliSense 的完整类型:

/*
type LongType = [] | ["A", "B", "C", "D", "E"] | ["B", "C", "D", "E"] | ["C", "D", "E"] |
  ["D", "E"] | ["E"] | ["D"] | ["C"] | ["C", "E"] | ["C", "D"] | ["B"] | ["B", "D", "E"] |
  ["B", "E"] | ... 18 more ... | [...]
*/

查看 ... 18 more ...[...] 截断。

您可以通过启用 the --noErrorTruncation compiler flag 来禁用此类截断。 (这是一个有点不幸的名字,因为它禁止在所有地方截断显示的类型名称,而不仅仅是在错误消息中。)然后你得到这个:

/* with --noErrorTruncation=true
type LongType = ["A", "B", "C", "D", "E"] | ["B", "C", "D", "E"] | ["C", "D", "E"] | 
  ["D", "E"] | ["E"] | [] | ["D"] | ["C", "E"] | ["C"] | ["C", "D"] | ["B", "D", "E"] | 
  ["B", "E"] | ["B"] | ["B", "D"] | ["B", "C", "E"] | ["B", "C"] | ["B", "C", "D"] | 
  ["A", "C", "D", "E"] | ["A", "D", "E"] | ["A", "E"] | ["A"] | ["A", "D"] | 
  ["A", "C", "E"] | ["A", "C"] | ["A", "C", "D"] | ["A", "B", "D", "E"] | 
  ["A", "B", "E"] | ["A", "B"] | ["A", "B", "D"] | ["A", "B", "C", "E"] | 
  ["A", "B", "C"] | ["A", "B", "C", "D"]
*/

Playground link to code