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.
}
132023 次浏览

我不能理解其背后的逻辑

我所理解的逻辑如下:

接口 Thing是一个要求将(非空、非未定义的) prop作为 string的契约。

如果一个人移除了财产,那么合同就不再实现了。

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

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

其背后的逻辑是,您需要使用如下可选属性来实现接口:

interface Thing {
prop?: string;
}
// OR
interface Thing {
prop: string | undefined;
}


function f(x: Thing) {
delete x.prop;
}

这样接口的契约就不会被破坏。

如果你希望它存在的话,还有另一个实现:

interface Thing {
prop: string;
}
interface PropoptionalThing {
prop?: string;
}


function f(x: Thing): PropoptionalThing {
let tmp: PropoptionalThing = x;
delete tmp.prop;
return tmp;
}

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中删除任何内容。

推荐

更具体地说,您可以使用 PartialBy(一个班轮)或 SetOptional(来自类型节点) :

  const y = { ...x } as PartialBy<Thing, 'prop1' | 'prop2'>;

这将使 prop1prop2成为可选的,但保持所有其他属性的原样。

注意

以上,我写了 const y = value as Type;,因为我发现它更容易阅读。但是您可能应该使用 const y: Type = value;,因为它确实执行 更好的类型检查

也许这个能帮上忙

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

你可以使用其他道具对象而不会爆发