如何在TypeScript中获取变量的静态类型,以便可以在另一个变量上使用它?
答案 0 :(得分:1)
使用typeof
。它的用法已从JavaScript扩展到可用于类型定义。
对于推断类型特别有用,例如下面的类型安全存根函数示例:
function realFunction() { return 123 }
// Compiles
const stub1: typeof realFunction = () => 456
// Does not Compile: wrong return type
const stub2: typeof realFunction = () => 'string'
答案 1 :(得分: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)