繁体   English   中英

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

[英]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'>;

这将使prop1prop2可选,但保留所有其他属性强制(必需)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM