简体   繁体   中英

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM