这是 typescript 代码中出现的新错误。
我无法意识到它背后的逻辑
Documentation
/*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.
}
最佳答案
I am not able to realize the logic behind it
我理解的逻辑如下:
接口(interface)
Thing
是要求具有(非空,非未定义)prop
的契约(Contract)作为 string
.如果一个人删除了属性(property),那么契约(Contract)就不再执行了。
如果您希望它在删除时仍然有效,只需使用
?
将其声明为可选: prop?: string
实际上,我很惊讶这并没有在早期版本的 TypeScript 中导致错误。
关于javascript - TypeScript 错误 "The operand of a ' delete' operator must be optional"背后的逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63702057/