我需要使用打字稿驗證 JSON。我想這樣做:
jsonFile.json
{
"foo": "bar",
"fiz": "baz",
"potato": 4
}
JSONType.ts
type JSONType = typeof jsonFile;
jsonFile2.json
{
"foo": 5,
"fiz": false
};
如果我這樣做:
const jsonFile2: JSONType = JSONFile2
我希望它因型別不匹配和缺少屬性而引發錯誤。
我本質上想確保兩個 JSON 具有相同的結構,其中一個作為事實來源。我怎么做?
uj5u.com熱心網友回復:
第一步是在 tsconfig.json 中允許 json 模塊"resolveJsonModule": true。下一步是匯入json檔案。
import file1 from './json/jsonFile.json'
import file2 from './json/jsonFile2.json'
現在,宣告您的型別并像您一樣應用它。
type JSONType = typeof file1;
const jsonFile2:JSONType = file2
它應該提示這個錯誤:
Property '"potato"' is missing in type '{ foo: number; fiz: boolean; }' but required in type '{ foo: string; fiz: string; potato: number; }'.ts(2741)
jsonFile.json(4, 5): '"potato"' is declared here.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388861.html
標籤:javascript json 打字稿
上一篇:從json解碼html字串
