javascript - ประเภทของ req และ res ใน express?
ในตัวอย่างนี้ฉันกำลังพยายามใช้ประเภท Response และ Request จาก DefinitelyTyped สำหรับพารามิเตอร์ req, res อย่างไรก็ตาม สิ่งนี้ไม่สามารถคอมไพล์ได้:
const express = require('express');
const app = express();
app.get('/', (req:Request, res:Response) => {
res.send('Hello Express Lovers!');
});
app.listen(3000, () => console.log('server started'));
ข้อผิดพลาดคือ:
^
TSError: ⨯ Unable to compile TypeScript:
index.ts:4:9 - error TS2339: Property 'send' does not exist on type'Response'.
คำตอบ #1
คุณควรนำเข้า Express ในแบบของ TypeScript เพื่อให้ประเภทของมัน (ใน @types/express) มาด้วย ทำให้ประเภทของ req และ res สามารถสรุปได้จาก app.get:
import * as express from 'express';
const app = express();
app.get('/', (req, res) => {
res.send('Hello Express Lovers!');
});
app.listen(3000, () => console.log('server started'));
เดโมที่อัปเดต
หากคุณต้องการพิมพ์พวกมันอย่างชัดเจนอยู่แล้ว คุณจะต้องนำเข้าประเภทเหล่านั้น:
import * as express from 'express';
import {Request, Response} from 'express';
const app = express();
app.get('/', (req: Request, res: Response) => {
res.send('Hello Express Lovers!');
});
app.listen(3000, () => console.log('server started'));
