繁体   English   中英

当使用 Javascript 从 object 删除密钥时,“删除”运算符的操作数必须是 optional.ts

[英]The operand of a 'delete' operator must be optional.ts when deleting a key from object with Javascript

我有一个 object 我在我的 React 应用程序的多个地方使用它:

   export default {
      'One': { Key: Foo.Bar, Color: '#eeeeaa' },
      'Two': { Key: Foo.Bar, Color: '#aaeeee' },
      'Three': { Key: Foo.Bar, Color: '#ffaaaa'},
    };

在一个特定的组件中,我需要这个 object 但没有键“三”。

当我尝试:

import MyObjects from './';

const newObject = delete MyObjects.Three;

我得到:

“删除”运算符的操作数必须是可选的。ts

如何解决这个问题或有更清洁的方法?

读这个:

“删除”运算符的操作数必须是可选的。

您需要使用接口以及可选键。 您可以创建一个具有特定接口类型的变量,而不是直接导出。

? 用于指示可选属性。 它们可以被删除(如您的错误所示)。

export interface Key {
 Key : string,
Color : string
}

export interface Colors {
     One : Key,
     Two : Key,
Three? : Key
}
const defaultColors : Colors = {
      'One': { Key: Foo.Bar, Color: '#eeeeaa' },
      'Two': { Key: Foo.Bar, Color: '#aaeeee' },
      'Three': { Key: Foo.Bar, Color: '#ffaaaa'},
    };
export default defaultColors;

另一种方法是创建一个仅包含两个 colors 的接口,然后创建一个扩展第一个接口的第二个接口(以及添加属性Three )。

暂无
暂无

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

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