从 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'

(link to playground)

data.animal 在几个地方使用,所以我尽量避免在任何地方使用 as Animal

解决此问题的最佳方法是什么?
有什么简单的方法可以告诉代码 data.animalAnimal?

这样做怎么样?

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;

您可以使用求和类型并合并 2 个定义 - 数据的原始定义和 animal:Animal 定义。

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