[英]The operand of a 'delete' operator must be optional.ts when deleting a key from object with Javascript
[英]What is the logic behind the TypeScript error "The operand of a 'delete' operator must be optional"?
這是 typescript 代碼中出現的新錯誤。
我無法意識到它背后的邏輯
文檔
/*When using the delete operator in strictNullChecks,
the operand must now be any, unknown, never, or be optional
(in that it contains undefined in the type). Otherwise, use of the delete operator is an error.*/
interface Thing {
prop: string;
}
function f(x: Thing) {
delete x.prop; // throws error = The operand of a 'delete' operator must be optional.
}
我無法理解其背后的邏輯
我理解的邏輯如下:
Interface Thing
是一個契約,要求將 (non-null, non-undefined) prop
作為string
。
如果移除該財產,則合同不再執行。
如果您希望它在刪除時仍然有效,只需將其聲明為可選的?
: prop?: string
我實際上很驚訝這並沒有在早期版本的 TypeScript 中導致錯誤。
這背后的邏輯是,您需要使用這樣的可選屬性來實現您的接口:
interface Thing {
prop?: string;
}
// OR
interface Thing {
prop: string | undefined;
}
function f(x: Thing) {
delete x.prop;
}
所以接口的契約不會被破壞。
也許這會有所幫助
const { propToDelete, ...otherProps} = youObject
return otherProps
這樣你就可以使用 otherProps object 而不會中斷
如果您希望它存在,則另一種實現:
interface Thing {
prop: string;
}
interface PropoptionalThing {
prop?: string;
}
function f(x: Thing): PropoptionalThing {
let tmp: PropoptionalThing = x;
delete tmp.prop;
return tmp;
}
這是打字稿代碼中出現的新錯誤。
我無法實現其背后的邏輯
文獻資料
/*When using the delete operator in strictNullChecks,
the operand must now be any, unknown, never, or be optional
(in that it contains undefined in the type). Otherwise, use of the delete operator is an error.*/
interface Thing {
prop: string;
}
function f(x: Thing) {
delete x.prop; // throws error = The operand of a 'delete' operator must be optional.
}
Thing
接口中的prop
屬性必須使用?
標記。
那么你的Thing
界面一定是這樣的。
interface Thing {
prop?: string;
}
您可以將x
的類型更改為部分:
function f(x: Partial<Thing>) {
delete x.prop;
}
但是我通常不喜歡改變(修改)從可能未知的代碼傳遞給我的對象。 所以我通常會創建一個新對象:
function f(x: Thing) {
const y = { ...x } as Partial<Thing>;
delete y.prop;
}
由於Partial
使所有屬性都是可選的,這將允許您從y
刪除任何內容。
如果您想獲得更具體的信息,可以使用typefest 中的SetOptional
:
const y = { ...x } as SetOptional<Thing, 'prop1' | 'prop2'>;
這將使prop1
和prop2
可選,但保留所有其他屬性強制(必需)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.