繁体   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