将 koa-views 与 TypeScript 结合使用

Using koa-views with TypeScript

我试图使用 koa-views 作为我的渲染器,但我一直收到来自 TS 的消息:

Property 'render' does not exist on type 'ParameterizedContext<any, IRouterParamContext<any, {}>>'.ts(2339)

我的app.js

import Koa from "Koa";
import views from "koa-views";
import indexRouter from "./routes/index"

const app = new Koa();

app.use(views(`${__dirname}/views`, { autoRender: true, extension: "swig" }));
app.use(indexRouter.routes());

index.js - IndexRouter:

import Router from "koa-router";
const router = new Router();

router.get("/", async (ctx, next) => {
  ctx.render(); // not done yet tho
  await next();
})

export = router;

这是因为参数 ctx 类型没有方法 render(),但在类型库中 @types/koa-views声明的模块(参见 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa-views/index.d.ts#L55)。

你可以这样做:

import { Context, DefaultState } from "koa";
import * as Router from "koa-router";

const router = new Router<DefaultState, Context>();

router.get("/", async (ctx: Context, next) => {
    await ctx.render("/path/");
    await next();
});