我試圖在我的 Express 專案中獲得一些更智能的輸入,但在擴展該Response.render功能時遇到了麻煩。
import { Response } from "express";
import { Product } from "../models/Product.interface";
export interface ProductListResponse extends Response {
render: (view: string, options?: { products: Product[] }) => void;
}
原點定義如下所示:
render(view: string, options?: object, callback?: (err: Error, html: string) => void): void;
render(view: string, callback?: (err: Error, html: string) => void): void;
當我嘗試編譯它時,我得到
src/routes/product.interface.ts:13:18 - error TS2430: Interface 'ProductListResponse' incorrectly extends interface 'Response<any, Record<string, any>>'.
Types of property 'render' are incompatible.
Type '(view: string, options: { products: Product[]; }) => void' is not assignable to type '{ (view: string, options?: object, callback?: (err: Error, html: string) => void): void; (view: string, callback?: (err: Error, html: string) => void): void; }'.
Types of parameters 'options' and 'callback' are incompatible.
Property 'products' is missing in type '(err: Error, html: string) => void' but required in type '{ products: Product[]; }'.
13 export interface ProductListResponse extends Response {
~~~~~~~~~~~~~~~~~~~
src/routes/product.interface.ts:14:37
14 render(view: string, options: { products: Product[] }): void;
~~~~~~~~
'products' is declared here.
Found 2 errors.
我以為我可以render通過擴展基本介面來覆寫 的定義,但顯然這不是真的。任何幫助將不勝感激。謝謝!
uj5u.com熱心網友回復:
您需要將介面的.render()方法多載簽名添加Response到您的自定義ProductListResponse介面中。
import express, { Response } from 'express';
interface Product {}
export interface ProductListResponse extends Response {
render(view: string, options?: { products: Product[] }): void;
render(view: string, options?: object, callback?: (err: Error, html: string) => void): void;
render(view: string, callback?: (err: Error, html: string) => void): void;
}
const app = express();
app.get('/', (req, res: ProductListResponse) => {
res.render('index', { products: [] });
});
或者,使用交集型別
import express, { Response } from 'express';
interface Product {}
export interface ProductListResponse {
render(view: string, options?: { products: Product[] }): void;
}
const app = express();
app.get('/', (req, res: ProductListResponse & Response) => {
res.render('index', { products: [] });
});
打字稿版本: 4.4.4
uj5u.com熱心網友回復:
您可以省略 renderexpress 的 Response 型別中的定義。然后,重新定義渲染函式:
interface ProductListResponse extends Omit<Response, 'render'> {
render: (view: string, options?: { products: Product[] }) => void;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/333162.html
