【问题标题】:How to get the type of a variable in TypeScript?如何在 TypeScript 中获取变量的类型?
【发布时间】:2020-04-13 19:56:31
【问题描述】:

如何在 TypeScript 中获取变量的静态类型,以便在另一个变量上使用它?

【问题讨论】:

    标签: typescript types mocking type-inference


    【解决方案1】:

    使用typeof。它的用途已从 JavaScript 扩展到类型定义。

    对推断类型特别有用,例如下面的类型安全存根函数示例:

    function realFunction() { return 123 }
    
    // Compiles
    const stub1: typeof realFunction = () => 456
    
    // Does not Compile: wrong return type
    const stub2: typeof realFunction = () => 'string'
    

    【讨论】:

      【解决方案2】:

      您的问题非常含糊,但从so you can use it on another variable? 的声明来看,我猜您正在寻找generics。在下面的示例中,<T> 是通用变量。它现在可以用作类型。调用此函数的任何人都可以定义 T 是什么。

      function doSomethignWithT<T>(arg: T): T {
        let newVariable: T;
        ...
        return arg;
      }
      
      doSomethignWithT<boolean>(true)
      

      【讨论】:

      • 如果您想要在同一函数中重用类型,则此答案有效。 typeof 解决方案适用于在其他上下文中重用类型。
      猜你喜欢
      • 2016-06-03
      • 2019-12-01
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 2012-07-03
      • 2016-12-03
      相关资源
      最近更新 更多