这是打字稿代码中出现的新错误。
我无法意识到它背后的逻辑
/*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.
}
原文由 Akshay Vijay Jain 发布,翻译遵循 CC BY-SA 4.0 许可协议
我理解的逻辑如下:
接口
Thing
是一个合约,要求有一个(非空,非未定义)prop
作为string
。如果一个人删除了财产,那么合同就不再执行了。
如果您希望它在删除时仍然有效,只需使用
?
将其声明为可选:prop?: string
实际上,我很惊讶这并没有在早期版本的 TypeScript 中导致错误。