84 lines
1.7 KiB
Plaintext
Raw Normal View History

== 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.
=== 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
// ...
}
----
=== 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
let x: MyUnionType;
2021-04-28 16:49:39 +02:00
function foo(value: string, padding: MyUnionType) {
// ...
}
----
=== Exceptions
2021-04-28 16:49:39 +02:00
This rule ignores union types part of ``++type++`` statement:
[source,javascript]
2021-04-28 16:49:39 +02:00
----
type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4;
----
It also ignores union types used with TypeScript utility types:
[source,javascript]
----
type PickedType = Pick<SomeType, 'foo' | 'bar' | 'baz' | 'qux'>;
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
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
endif::env-github,rspecator-view[]
== Resources
=== Documentation
* https://www.typescriptlang.org/docs/handbook/utility-types.html[TypeScript Utility Types]