簡體   English   中英

從 JSON 文件推斷字符串文字類型

[英]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.animalAnimal嗎?

您可以使用總和類型並合並 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM