TypeScript 错误“'delete' 运算符的操作数必须是可选的”背后的逻辑是什么?

新手上路,请多包涵

这是打字稿代码中出现的新错误。

我无法意识到它背后的逻辑

文档

/*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 许可协议

阅读 6.3k
2 个回答

我无法意识到它背后的逻辑

我理解的逻辑如下:

接口 Thing 是一个合约,要求有一个(非空,非未定义) prop 作为 string

如果一个人删除了财产,那么合同就不再执行了。

如果您希望它在删除时仍然有效,只需使用 ? 将其声明为可选: prop?: string

实际上,我很惊讶这并没有在早期版本的 TypeScript 中导致错误。

原文由 Pac0 发布,翻译遵循 CC BY-SA 4.0 许可协议

也许这会有所帮助

const { propToDelete, ...otherProps} = youObject
return otherProps

这样您就可以使用 otherProps 对象而不会中断

原文由 Edgar Olivar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题