84 lines
1.7 KiB
Plaintext
84 lines
1.7 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
With the default threshold of 3:
|
|
|
|
[source,javascript]
|
|
----
|
|
let x: MyType1 | MyType2 | MyType3 | MyType4; // Noncompliant
|
|
|
|
function foo(p1: string, p2: MyType1 | MyType2 | MyType3 | MyType4) { // Noncompliant
|
|
// ...
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,javascript]
|
|
----
|
|
type MyUnionType = MyType1 | MyType2 | MyType3 | MyType4; // Compliant, "type" statements are ignored
|
|
let x: MyUnionType;
|
|
|
|
function foo(value: string, padding: MyUnionType) {
|
|
// ...
|
|
}
|
|
----
|
|
|
|
|
|
=== Exceptions
|
|
|
|
This rule ignores union types part of ``++type++`` statement:
|
|
|
|
[source,javascript]
|
|
----
|
|
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]
|