Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - What is the logic behind the TypeScript error "The operand of a 'delete' operator must be optional"?

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.
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I am not able to realize the logic behind it

The logic as I understand is the following:

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.

If you want it still valid when removed, just declare it as optional with a ?: prop?: string

I'm actually surprised that this was not causing error in earlier versions of TypeScript.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...