【问题标题】:Typescript: Visualize type, i.e. show type's signatureTypescript:可视化类型,即显示类型的签名
【发布时间】:2019-02-21 10:29:47
【问题描述】:

当我们想查看变量的值时,我们只需要console.log(someVar)

如果我们想看看 type 背后是什么?

例子:

type SomeUnion = 'foo' | 'bar' | 'baz'

console.log(SomeUnion) 
// of course above will not work, but what will do?
// is there any TS tool that I am missing?

附:对于那些可能不明白为什么需要这个的人,这里有一个更复杂的类型(来自TS docs):

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

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

type T40 = FunctionPropertyNames<Part>;  // "updatePart"

最后一行注释了类型的样子。目前我正在做什么来确定它是否真的看起来像这样:

let foo: T40 = 'bar' // gives error: type "bar" is not assignable to type "updatePart"

换句话说,知道隐藏在类型标识符后面的唯一方法是生成类型错误,这不应该是唯一的方法。

【问题讨论】:

  • 我认为没有任何工具可以静态地执行此操作,但您可以尝试创建对象的实例并在其上调用 Object.keys()。看到这个stackoverflow.com/a/43910186/1486848

标签: typescript


【解决方案1】:

如果您使用playground (current caveat) 或支持 TypeScript 语言服务的 IDE(例如 Visual Studio Code),您只需将鼠标悬停在 type T40 = FunctionPropertyNames&lt;Part&gt;; 中的 T40 上即可查看类型的扩展.

【讨论】:

  • 大多数情况下,有时,对于某些类型......它在这种情况下有效,但我的经验是该类型并不总是完全扩展,总比没有好:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
  • 2013-08-03
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
相关资源
最近更新 更多