2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
Union types represent a value that can be one of the several types. When a union type is used for a function parameter and it is accepting too many types, it may indicate the function is having too many responsibilities. Sometimes it's worth creating a type alias for this union type. In all cases, the code should be reviewed and refactored to make it more maintainable.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
With the default threshold of 3:
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
let x: MyType1 | MyType2 | MyType3 | MyType4; // Noncompliant
function foo(p1: string, p2: MyType1 | MyType2 | MyType3 | MyType4) { // Noncompliant
// ...
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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
----
type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4; // Compliant, "type" statements are ignored
2022-08-04 15:12:16 +02:00
let x: MyUnionType;
2021-04-28 16:49:39 +02:00
function foo(value: string, padding: MyUnionType) {
// ...
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Exceptions
2021-04-28 16:49:39 +02:00
This rule ignores union types part of ``++type++`` statement:
2022-08-04 15:12:16 +02:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4;
----
2021-04-28 18:08:03 +02:00
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
2021-09-20 15:38:42 +02:00
2023-05-25 14:18:12 +02:00
Refactor this union type to have less than X elements.
=== Parameters
.max
****
----
3
----
Maximum elements authorized in a union type definition.
****
=== Highlighting
All the elements of the union type
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]