如何在TypeScript中获取变量的类型?

问题描述 投票:0回答:2

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

typescript types mocking type-inference
2个回答
1
投票

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

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

function realFunction() { return 123 }

// Compiles
const stub1: typeof realFunction = () => 456

// Does not Compile: wrong return type
const stub2: typeof realFunction = () => 'string'

0
投票

您的问题非常模糊,但是从语句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)
© www.soinside.com 2019 - 2024. All rights reserved.