typescript - 有沒有什麼方法可以在 Deno 中將 json 文件轉換為對象模型?
問題:當我嘗試讀取一個文件(student.json)並將其存儲在類型為 Student[] 的變量中時,它顯示“Type 'unknown' is not assignable to type 'Student[]'.”。這是一個 TypeScript 文件。
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);
};
期望:我正在嘗試將檔案中的 JSON 返回到伺服器。嘗試的解決方案:我已經嘗試了 Json.stringify()。它仍然給我相同的錯誤。
答案#1
readJson 方法返回未知類型的 promise。未知類型只能賦值給 any 類型和未知類型本身。
如果你想強制編譯器相信一個未知類型的值是某個特定類型,你可以使用如下的類型斷言:
const f = await readJson("./public/student.json");
const students:Student[] = f as Student[];
答案#2
要解決上述錯誤,只需使用類型斷言:
const students = f as Student[];
我對 deno 不熟悉,但我很確定你可以直接將檔案寫入回應流,或是使用適當的標頭來提供它。不確定這對你的情境是否有意義。
