65 lines
1.8 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
In TypeScript there are several ways to declare a property with ``++undefined++`` value: adding ``++| undefined++`` in the property type or using optional property syntax (``++?++`` after its name). Use ``++| undefined++`` syntax when you want to be explicit that an object has that property, in that case TypeScript compiler will not allow omitting it:
----
interface Person {
name: string;
address: string | undefined;
}
let John = { name: "John" }; // will not compile
let John = { name: "John", address: undefined }; // will compile, we want to be explicit when person does not have home
----
Use optional property syntax for properties holding some additional information.
----
interface Person {
name: string;
pet?: string;
}
let John = { name: "John" }; // will compile
let John = { name: "John", pet: undefined }; // will compile, there is no pet like for the object on previous line
let John = { name: "John", pet: "Benji" }; // will compile
----
Using ``++| undefined++`` for optional property is redundant, it can be omitted without change to the actual type. Still if you want to force the property in the object consider using only ``++| undefined++`` without ``++?++``.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
interface Person {
name: string;
address? : string | undefined; // Noncompliant, "?" should be removed
pet?: Animal | undefined; // Noncompliant, "undefined" should be removed
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
interface Person {
name: string;
address: string | undefined;
pet?: Animal;
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]