2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-07-27 11:45:31 +02:00
In TypeScript, there are two ways to define properties or parameters that are potentially ``++undefined++``:
2021-04-28 16:49:39 +02:00
2023-07-27 11:45:31 +02:00
* 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]
2021-04-28 16:49:39 +02:00
----
interface Person {
name: string;
address: string | undefined;
}
2023-07-27 11:45:31 +02:00
let John = { name: "John", address: undefined };
2021-04-28 16:49:39 +02:00
----
2023-07-27 11:45:31 +02:00
* 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`.
2021-04-28 16:49:39 +02:00
2023-07-27 11:45:31 +02:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
interface Person {
name: string;
2023-07-27 11:45:31 +02:00
address?: string;
2021-04-28 16:49:39 +02:00
}
2023-07-27 11:45:31 +02:00
let John = { name: "John" };
2021-04-28 16:49:39 +02:00
----
2023-07-27 11:45:31 +02:00
This rule checks for optional property declarations that use both the `?` syntax and unions with `undefined`.
2021-04-28 16:49:39 +02:00
2023-07-27 11:45:31 +02:00
[source,javascript,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
interface Person {
name: string;
2023-07-27 11:45:31 +02:00
address?: string | undefined; // Noncompliant: using both syntaxes is redundant
2021-04-28 16:49:39 +02:00
}
----
2023-07-27 11:45:31 +02:00
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.
2021-04-28 18:08:03 +02:00
2023-07-27 11:45:31 +02:00
[source,javascript,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
interface Person {
name: string;
2023-07-27 11:45:31 +02:00
address?: string;
2021-04-28 16:49:39 +02:00
}
----
2021-04-28 18:08:03 +02:00
2023-07-27 11:45:31 +02:00
== Resources
=== Documentation
* https://www.typescriptlang.org/docs/handbook/2/objects.html#optional-properties[TypeScript - Optional Properties]
* https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types[TypeScript - Union Types]
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Consider removing 'undefined' type or '?' specifier, one of them is redundant.
=== Highlighting
Primary: "?"
Secondary: "undefined"
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]