我正在读取一个大的 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'
(链接到游乐场 https://www.typescriptlang.org/play?#code/C4TwDgpgBAggdgSwLYEMA2UC8UDkAjCFAJxygB9cBjFYUinAEwHsBzHAbgChPKm4BnYFAY0UWKAG9OUKHBRIIALlwBZFAA8cAGmlQULJVADMOmSkSo0yxq226A9PagBGAAyv%20UJsAAWEIlBgREyQRMAIEJ4AZsFIUABSAMoA8gByUFEIaBAAdHmcAL5cnNlCvhCp8oaCRAhwLOIiwCg5cgrsUI6B-lEQlMAlEGV%20MAbKcACuSAQB2E0t%20hAdXaG9-YPDEPDI6Mrblo2iOeY7aMtOAKJEwUTKACrg0Dg1dWxQCJ5w3nr8-Agscjw2SgwCYIMeuH26BwnCAA)
data.animal
在几个地方使用,所以我试图避免使用as Animal
到处。
解决这个问题的最佳方法是什么?
有什么简单的方法可以告诉代码data.animal
is an 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)