本文介绍了TypeScript 错误“‘删除’操作符的操作数必须是可选的"背后的逻辑是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是打字稿代码中出现的新错误.
This is the new error that is coming in typescript code.
我无法理解其背后的逻辑
文档
I am not able to realize the logic behind it
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.
}
推荐答案
据我所知,逻辑如下:
Interface Thing
是一个契约,要求将(非空,非未定义)prop
作为 string
.
Interface Thing
is a contract asking to have a (non-null, non-undefined) prop
as a string
.
如果移除财产,则合同不再执行.
If one removes the property, then the contract is not implemented anymore.
如果您希望它在删除后仍然有效,只需使用 ?
将其声明为可选:prop?: string
If you want it still valid when removed, just declare it as optional with a ?
: prop?: string
我实际上很惊讶这并没有在早期版本的 TypeScript 中导致错误.
I'm actually surprised that this was not causing error in earlier versions of TypeScript.
这篇关于TypeScript 错误“‘删除’操作符的操作数必须是可选的"背后的逻辑是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!