58 lines
2.2 KiB
Plaintext
58 lines
2.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In TypeScript, unions and intersections are used to combine multiple types into a single type, allowing you to create more flexible and powerful type definitions.
|
|
|
|
* A union type is represented using the pipe symbol ``++|++``. It allows you to declare a variable or parameter that can hold values of different types. The variable can be assigned a value of any type listed in the union.
|
|
* An intersection type is represented using the ampersand symbol ``++&++``. It allows you to combine multiple types into a single type that includes all the properties and methods from each type.
|
|
|
|
Having duplicated constituents in TypeScript unions and intersections can lead to undesirable behavior and potential issues in your code. TypeScript's type system aims to provide a strong and sound static type checking to catch errors during development and improve code reliability. Including duplicate constituents in unions or intersections can make the type definitions unnecessarily verbose and redundant. This makes the code harder to read and maintain.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
function padLeft(value: string, padding: string | number | string) { // Noncompliant: 'string' type is used twice in a union type declaration
|
|
// ...
|
|
}
|
|
|
|
function extend(p : Person) : Person & Person & Loggable { // Noncompliant: 'Person' is used twice
|
|
// ...
|
|
}
|
|
----
|
|
|
|
Define unions and intersections with distinct and non-repeating constituents. This will make your code cleaner and more precise.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
function padLeft(value: string, padding: string | number | boolean) {
|
|
// ...
|
|
}
|
|
|
|
function extend(p : Person) : Person & Loggable {
|
|
// ...
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html[Unions and Intersection Types]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Remove this duplicated type or replace with another one.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
First: second occurrence of the element
|
|
|
|
Second: first occurrence ("Original"), third and all other occurrences ("Another duplicate")
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|