简体   繁体   English

如何从 TypeScript 中的另一个模块引用现有类型?

[英]How can I refer to an existing type from another module in TypeScript?

Supposed I am writing a Node.js hello world server.假设我正在编写一个 Node.js hello world 服务器。 Then as the callback to the http.createServer function I have a function that basically looks like this:然后作为对http.createServer函数的回调,我有一个基本上如下所示的函数:

(req, res) => {
  // ...
}

Now, if I want to do this in TypeScript I would like to tell the compiler that req and res are the appropriate objects from Node.js.现在,如果我想在 TypeScript 中执行此操作,我想告诉编译器reqres是来自 Node.js 的适当对象。 How do I add these as types?如何将这些添加为类型? Basically this has to look like this:基本上这必须是这样的:

(req: X, res: Y): void => {
  // ...
}

But what do I have to provide for X and Y ?但是我必须为XY提供什么? I don't want to recreate everything from scratch, and I suppose there has to be some mechanism to refer to an existing type, hasn't it?我不想从头开始重新创建所有内容,我想必须有某种机制来引用现有类型,不是吗?

I suppose that the types for req and res have already been defined somewhere, eg in @types/node .我想reqres的类型已经在某处定义了,例如在@types/node How do I use one of those types defined there in my own code?我如何使用在我自己的代码中定义的那些类型之一?

In http.d.ts , RequestListener type is declared.http.d.ts ,声明了RequestListener类型。

type RequestListener = (req: IncomingMessage, res: ServerResponse) => void;

You can import those types from http module.您可以从http模块导入这些类型。

import { IncomingMessage, ServerResponse } from 'http';

const requestListener = (req: IncomingMessage, res: ServerResponse): void => {
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM