简体   繁体   English

打字稿嵌套动态属性

[英]Typescript nested dynamic properties

I've been trying to improve the types of an older project that uses a lot of 'any' whenever things get complicated.我一直在尝试改进一个旧项目的类型,该项目在事情变得复杂时使用大量“任何”。

Replit-link复制链接

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):考虑以下不规则数据结构,其中 Data 是与示例匹配的接口(有些是嵌套对象,有些不是。我在所有页面上使用相同的映射函数,具体取决于 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: keyof typeof data将返回此文字类型:

'car' | 'cat' | 'random' | 'why'

Which you could consume it like:你可以这样消费它:

localData[key] = data[nestedKey][key]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM