![](/img/trans.png)
[英]What is the logic behind the TypeScript error "The operand of a 'delete' operator must be optional"?
[英]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.