[英]Typescript augmentation with fluent API
I have some express module augmentations. 我有一些快速模块增强。 My intention is to be able to do:
我的意图是能够做到:
request.message('Hello').status(400).json({});
The status
and json
functions are part of the express Response
object. status
和json
函数是快速Response
对象的一部分。 These functions return the Response
object they were called on to allow chaining (aka a fluent API). 这些函数返回被调用以允许链接(也称为流利的API)的
Response
对象。
I wish to add my own message
function to do much the same. 我希望添加自己的
message
功能以执行相同的操作。 My augmentation looks like so: 我的扩充看起来像这样:
import { SomeType } from '...';
declare global {
namespace Express {
interface Response {
// This works.
getSomeType(): SomeType;
// This does not. Typescript thinks the object returned here has ONLY the getSomeType/message functions on it
message(str: string): Response;
}
}
I've tried variations of 我试过了
message(str: string): Express.Response
And 和
message(str: string): Response & Express.Response
This made no difference. 这没什么区别。 As before: Typescript thinks the object returned here has ONLY the getSomeType/message functions on it
如前所述:Typescript认为此处返回的对象仅具有getSomeType / message函数
Ok, found the solution. 好的,找到解决方案。 I needed to import express into my type augmentation, and make my augmentation return
express.Response
: 我需要将express导入我的类型扩充中,并使扩充返回
express.Response
:
import { SomeType } from '...';
import express from 'express';
declare global {
namespace Express {
interface Response {
getSomeType(): SomeType;
message(str: string): express.Response;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.