【问题标题】:Is there any way to print a resolved TypeScript type?有没有办法打印已解析的 TypeScript 类型?
【发布时间】:2018-06-12 09:18:11
【问题描述】:

我正在阅读有关 TypeScript 2.8 - Conditional Types 的信息,我在 Typescript 文档中看到了很多示例,它们将类型的 resolved? 版本列为其旁边的 cmets:

type TypeName<T> =
    T extends string ? "string" :
    T extends number ? "number" :
    T extends boolean ? "boolean" :
    T extends undefined ? "undefined" :
    T extends Function ? "function" :
    "object";

type T0 = TypeName<string>;  // "string"
type T1 = TypeName<"a">;  // "string"
type T2 = TypeName<true>;  // "boolean"
type T3 = TypeName<() => void>;  // "function"
type T4 = TypeName<string[]>;  // "object"

例如TypeName&lt;true&gt; 实际上是boolean。这在更复杂的场景中变得更加有用,您可以在其中查看您实际构建的类型:

type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];
type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;

type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;

interface Part {
    id: number;
    name: string;
    subparts: Part[];
    updatePart(newName: string): void;
}

type T40 = FunctionPropertyNames<Part>;  // "updatePart"
type T41 = NonFunctionPropertyNames<Part>;  // "id" | "name" | "subparts"
type T42 = FunctionProperties<Part>;  // { updatePart(newName: string): void }
type T43 = NonFunctionProperties<Part>;  // { id: number, name: string, subparts: Part[] }

当出现关于类型的混淆时,这当然可以帮助我,所以我想知道是否有任何方法可以让编译器提取相同的类型信息?

【问题讨论】:

  • 您的意思是在 vs 代码中悬停在一个类型上以查看解析的类型?您是否需要某种命令行实用程序使用编译器 API 来执行此操作?
  • @TitianCernicova-Dragomir 我没用过 VS 代码,它已经提供这个功能了吗?
  • 是的,如果有帮助,我可以通过屏幕截图提供答案:)
  • @TitianCernicova-Dragomir 啊,很好,我不知道。是的,那太好了:)
  • 相关答案:使用invalid assignment trick,使用ts-node,或使用compiler API。也看看Implementing an Expand&lt;T&gt; type

标签: typescript types


【解决方案1】:

如果您将鼠标悬停在条件类型上,Visual Studio 代码已经提供了此功能。对于您的示例,这就是它的样子:

【讨论】:

    猜你喜欢
    • 2017-04-26
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 2020-08-17
    • 2022-01-06
    相关资源
    最近更新 更多