Search code examples
typescriptdenotype-assertion

Is there some way to convert a json file to an object model in Deno?


Issue: When i try to read a file (student.json) and store it in a variable of type Student[] it says "Type 'unknown' is not assignable to type 'Student[]'." This is a typescript file.

import { Student } from "../Models/studentModel.ts";
import { readJson, writeJson } from "https://deno.land/std/fs/mod.ts";

const f = await readJson("../public/student.json");
const students:Student[] = f;

export const get_all_students = (ctx: Context) => {
  return ctx.json(students,200);
};

Expectation: I am trying to return the json from the file to the server. Solutions tried: I have tried Json.stringify(). It still gives me the same error.


Solution

  • To solve the above error just use a type assertion:

    const students = f as Student[];
    

    I'm not familiar with deno, but pretty sure you could just write the file to response stream or serve it with appropriate headers. Not sure if that makes sense for your scenario.