node.jstypescriptkoakoa2

Using koa-views with TypeScript


I was trying to use koa-views as my renderer, but I kept getting the message from TS:

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

My 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;

Solution

  • This is because argument ctx type doesn't have method render(), but in types lib @types/koa-views declared module (see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/koa-views/index.d.ts#L55).

    And you can make this:

    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();
    });