我正在讀取一個大型 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嗎?
uj5u.com熱心網友回復:
您可以使用總和型別并合并 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
uj5u.com熱心網友回復:
這樣做怎么樣?
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315198.html
