【发布时间】:2021-10-14 06:06:17
【问题描述】:
我正在读取一个大型 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。
解决此问题的最佳方法是什么?
有什么简单的方法可以告诉代码data.animal 是Animal?
【问题讨论】:
标签: typescript string-literals