78 lines
2.3 KiB
Plaintext
78 lines
2.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In TypeScript, there are two ways to define properties or parameters that are potentially ``++undefined++``:
|
|
|
|
* Union with `undefined`: Adding ``++| undefined++`` in the property type makes the property __required__, but can be `undefined`. Use this syntax when you want to be explicit that an object should provide that property, in which case the TypeScript compiler will not allow omitting it.
|
|
|
|
[source,javascript]
|
|
----
|
|
interface Person {
|
|
name: string;
|
|
address: string | undefined;
|
|
}
|
|
|
|
let John = { name: "John", address: undefined };
|
|
----
|
|
|
|
* Optional property syntax (``++?++`` after its name): The property is __optional__, which means that an object can omit it and let the TypeScript compiler provide it as being `undefined`.
|
|
|
|
[source,javascript]
|
|
----
|
|
interface Person {
|
|
name: string;
|
|
address?: string;
|
|
}
|
|
|
|
let John = { name: "John" };
|
|
----
|
|
|
|
This rule checks for optional property declarations that use both the `?` syntax and unions with `undefined`.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
interface Person {
|
|
name: string;
|
|
address?: string | undefined; // Noncompliant: using both syntaxes is redundant
|
|
}
|
|
----
|
|
|
|
Choose one of the syntaxes to declare optional properties and remove the other one. Consider using only ``++| undefined++`` if you want to make the property explicit in the object.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
interface Person {
|
|
name: string;
|
|
address?: string;
|
|
}
|
|
----
|
|
|
|
The rule does not raise any issues when the TypeScript compiler option `exactOptionalPropertyTypes` is enabled because this option ensures that `undefined` does not become redundant in this context.
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties[Optional Properties]
|
|
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types[Union Types]
|
|
* TypeScript Documentation - https://www.typescriptlang.org/tsconfig/#exactOptionalPropertyTypes[exactOptionalPropertyTypes]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Consider removing 'undefined' type or '?' specifier, one of them is redundant.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
Primary: "?"
|
|
|
|
Secondary: "undefined"
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|