koa2如何引入typescript支持?

koa2如何引入typescript支持

import * as Koa2 from "koa2";

router.get('/', (ctx: Koa2.Context, next: Koa2.Next) => {
  // 这里使用ctx.的时候不会有提示,如何让ctx.有提示
  // console.log(ctx.)
})

尝试了安装@types/koa包,没有效果,期望ctx.的时候有提示

阅读 429
1 个回答
✓ 已被采纳

image.png

{
  "dependencies": {
    "@koa/router": "^13.1.0",
    "koa": "^3.0.0"
  },
  "devDependencies": {
    "@types/koa": "^2.15.0",
    "@types/koa__router": "^12.0.4",
    "typescript": "^5.8.3"
  }
}
// index.ts
import Koa, { Context, Next } from 'koa';
import Router from '@koa/router';

const app = new Koa();
const router = new Router();

// 这里 ctx: Context 就会有完整的提示
router.get('/', async (ctx: Context, next: Next) => {
  ctx.body = 'Hello Koa';
  await next();
});

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
});

推荐问题