gpt4 book ai didi

express - 扩展 TypeScript 声明文件

转载 作者:搜寻专家 更新时间:2023-10-30 21:53:17 26 4
gpt4 key购买 nike

我正在尝试使用 TypeScript 和 Express。我已经从 Typings 加载了类型声明,它们看起来像这样:

// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/express/express.d.ts
declare module "express" {
import * as serveStatic from "serve-static";
import * as core from "express-serve-static-core";

/**
* Creates an Express application. The express() function is a top-level function exported by the express module.
*/
function e(): core.Express;

namespace e {

/**
* This is the only built-in middleware function in Express. It serves static files and is based on serve-static.
*/
var static: typeof serveStatic;

export function Router(options?: any): core.Router;

interface Application extends core.Application { }
interface CookieOptions extends core.CookieOptions { }
interface Errback extends core.Errback { }
interface ErrorRequestHandler extends core.ErrorRequestHandler { }
interface Express extends core.Express { }
interface Handler extends core.Handler { }
interface IRoute extends core.IRoute { }
interface IRouter<T> extends core.IRouter<T> { }
interface IRouterMatcher<T> extends core.IRouterMatcher<T> { }
interface MediaType extends core.MediaType { }
interface NextFunction extends core.NextFunction { }
interface Request extends core.Request { }
interface RequestHandler extends core.RequestHandler { }
interface RequestParamHandler extends core.RequestParamHandler { }
export interface Response extends core.Response { }
interface Router extends core.Router { }
interface Send extends core.Send { }
}

export = e;
}

现在我正尝试像这样扩展所有 Response 对象的原型(prototype):

const express = require('express');
express.response.sendWrapped = function(obj: Object, meta?: Object) {
return this.json({
data: obj
});
};

现在我只需要将扩展​​名放入类型中。我很想将此方法扩展到现有定义中,就像我在原型(prototype)中扩展它的方式一样,但我不确定该怎么做。

由于这是库类型定义的个人扩展,我相信这属于主打字集,我应该必须修改出于我自己的目的手动处理它们。以我自己的方式扩展它们的最佳方式是什么?我可以在不覆盖依赖于 Response 的所有其他部分的情况下做到这一点吗?

最佳答案

使用 TypeScript 2.0 或其预发布版 (typescript@next),您可以使用模块扩充语法来扩充 express 的定义,以包含您的新 response 定义:

import express = require('express');

declare module "express" {
namespace response {
function sendWrapped(obj: any, meta?: any): void;
}
}

express.response.sendWrapped = function(obj: Object, meta?: Object) {
return this.json({
data: obj
});
};

关于express - 扩展 TypeScript 声明文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37505881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com