[英]Infer string literal type from a JSON file
我正在讀取一個大型 JSON 文件。
TypeScript 足夠聰明,可以推斷除一個之外的所有屬性的類型。
一個簡化的例子:
type Animal = 'bear' | 'cat' | 'dog';
const data = {
name: 'Max',
age: 3,
animal: 'dog',
// 100s other properties from JSON file...
};
let theName: string = data.name; // perfect
let theAge: number = data.age; // perfect
let theAnimal: Animal = data.animal; // Error: Type 'string' is not assignable to type 'Animal'
( 鏈接到操場)
data.animal
在幾個地方使用,所以我試圖避免as Animal
任何地方使用as Animal
。
解決此問題的最佳方法是什么?
有什么簡單的方法可以告訴代碼data.animal
是Animal
嗎?
您可以使用總和類型並合並 2 個定義 - 數據的原始定義和動物:動物定義。
type Animal = 'bear' | 'cat' | 'dog';
// the keys your want to exert
type DataWithAnimal = { [P in 'animal']: Animal } ;
const data = {
name: 'Max',
age: 3,
animal: 'dog',
// 100s other properties from JSON file...
};
// original data type
type DataType = typeof data;
// merge the 2 type definitions
type Data = DataType & DataWithAnimal;
// cast old type to new type
const typeData: Data = data as Data;
let theName: string = typeData.name; // perfect
let theAge: number = typeData.age; // perfect
let theAnimal: Animal = typeData.animal; // also perfect
這樣做怎么樣?
type Animal = 'bear' | 'cat' | 'dog';
type Data = {
name: string;
age: number;
animal: Animal;
}
const data: Data = {
name: 'Max',
age: 3,
animal: 'dog',
// 100s other properties from JSON file...
};
let theName: string = data.name; // perfect
let theAge: number = data.age; // perfect
let theAnimal: Animal = data.animal;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.