如何在 TypeScript 的模块中找到 类 的名称

How do I find the names of classes in modules for TypeScript

所以在这段代码中:

import * as fs from "fs"

class FsAsyncFactory {

    private static fsSync: any

}

export default FsAsyncFactory

我已将此道具 private static fsSync: any 的类型设置为 any 但它将成为在顶部导入的 fs 变量 - 我如何确定 class叫什么?

我猜到了类似 FileSystem 的结果,但没有成功。我对 TypeScript 的理解不够深入,无法弄清楚。

我的开发依赖项中有 "@types/node": "^8.0.50",,我已经进入 node_modules/@types/node/index.d.ts 但我看不到任何有意义的东西?谢谢!

可以使用typescript的"type of"命令

import * as fs from "fs"

class FsAsyncFactory {

   private static fsSync: typeof fs

}

export default FsAsyncFactory

然后在你的class

里面
constructor(){
 //...//
 FsAsyncFactory.fsSync. //ide recognizes fsSync is of type "fs" and gives you full prediction of fs functions
 //...//
}

问题:这个 typeof 是什么,为什么我不能只使用 class 名称?

基本上,据我阅读 node/index.d.ts 的理解,fs 只是一个正在导出的模块。基本上是一个带有一些类型化函数的对象,它们有自己的文档。在那种情况下,我们没有 class 名称或接口来声明等于 fs 的其他变量。打字稿的 typeof 命令是一个 类型查询 ,基本上如果没有 class 或在源变量上实现接口,它只会期望与源相同的属性将呈现在目标中。

解决您的问题的另一种方法可能是使用 类型别名

import * as fs from "fs"
type FileSystem = typeof fs

class FsAsyncFactory {

   private static fsSync: FileSystem

}

export default FsAsyncFactory

这将创建一个名为 FileSystem 的新类型,它将期望声明为 FileSystem 类型的每个对象实现 fs 模块的每个功能。

问题:如何将 Bluebird 的 promisifyAll 与 typescript 一起使用?

import * as fs from "fs"
import * as Bluebird from "bluebird"

const fsProm : FileSystem = Bluebird.promisifyAll(fs)

fsProm.writeFile('filename','some data') // Typescript error function expects at least 3 parameters
   .then(console.log) 

不幸的是,从我的角度来看,promisifyAll 会将严格类型化的函数更改为其他函数,而不会留下任何更改内容的定义,这对打字稿来说非常糟糕。经过一番搜索后,我找不到任何适用于所有情况的可靠解决方案,请查看此 issue。 也许您最好的选择是将您的 promisidied 变量声明为类型 any 并在没有智能感知的情况下继续工作。