作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下 TypeScript 枚举:
export declare enum SupportedLanguages {
en,
fr
}
如果我将它导入到我的 React 应用程序中并 console.log
它,我将返回以下对象:
{
en: "en",
fr: "fr"
}
我如何操作它,以便返回以下对象?
{
en: "",
fr: ""
}
我用 const Lang = Object.keys(SupportedLanguages)
和 .map()
试过了,但我没有得到预期的对象返回。
最佳答案
您可以获得键,并将它们映射到 [key, '']
的元组,然后使用 Object.fromEntries()
转换回对象:
const supportedLanguages = {
en: "en",
fr: "fr"
};
const result = Object.fromEntries(
Object.keys(supportedLanguages)
.map(k => [k, ''])
);
console.log(result);
如果您收到这样的错误:
TS2550: Property 'fromEntries' does not exist on type 'ObjectConstructor'. Do you need to change your target library? Try changing the
lib
compiler option to 'es2019' or later.
将es2019
添加到项目的tsconfig.json
中的compilerOptions.lib
:
{
"compilerOptions": {
"lib": [
"es2019"
]
}
}
关于javascript - 特定对象的 TypeScript 枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59286783/
我是一名优秀的程序员,十分优秀!