Surya Datta
Surya Datta

Reputation: 23

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.

Upvotes: 2

Views: 753

Answers (2)

Chellappan வ
Chellappan வ

Reputation: 27439

readJson method return promise type of unknown. The unknown type is only assignable to the any type and the unknown type itself.

If you want to force the compiler to trust you that a value of type unknown is of a given type, you can use a type assertion like this:

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

Upvotes: 1

Aleksey L.
Aleksey L.

Reputation: 37986

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.

Upvotes: 0

Related Questions