I've been trying to improve the types of an older project that uses a lot of 'any' whenever things get complicated.
Consider the following irregular data structure where Data is an interface matching the example (some are nested objects, some are not. I use the same mapping function on all pages, depending on what is present in localData):
const data: Data = {
car: { name: 'x', speed: 45},
cat: { fur: true },
random: ['hi', 'bye']
why: "because"
};
Now I'm mapping this data on different pages like so
const nestedKey = 'car';
const localData = {
name: '',
speed: 0
};
Object.keys(localData).forEach(key => {
if (nestedKey && data[nestedKey]) {
// Here I'm not too sure what type to give key to make TS happy
localData[key] = data[nestedKey as keyof Data][key]
} else {
localData[key] = data[key as keyof Data]
}
});
const nestedKey: keyof typeof data = 'car';
keyof typeof data
will return this literal type:
'car' | 'cat' | 'random' | 'why'
Which you could consume it like:
localData[key] = data[nestedKey][key]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.