
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
68 lines
1.8 KiB
Plaintext
68 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
A common idiom in JavaScript to differentiate between two possible types is to check for the presence in the object of a member of the desired type. Usually, to simplify the code, a boolean function is created to check the type.
|
|
|
|
Typescript provides user defined type guard functions. These are just functions with a return type of ``++argumentName is SomeType++``. Such functions return ``++true++`` if the argument is of the specified type. One of the advantages of using such a function is that in a conditional block where the condition is a type guard, the compiler automatically performs the appropriate casts, so explicit casting becomes unnecessary.
|
|
|
|
|
|
This rule raises an issue when a boolean function checking for the type of its only argument can be replaced with a user-defined type guard function.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,javascript]
|
|
----
|
|
function isSomething(x: BaseType) : boolean { // Noncompliant
|
|
return (<Something>x).foo !== undefined;
|
|
}
|
|
|
|
if (isSomething(v)) {
|
|
(<Something>v).foo();
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,javascript]
|
|
----
|
|
function isSomething(x: BaseType) : x is Something {
|
|
return (<Something>x).foo !== undefined;
|
|
}
|
|
|
|
if (isSomething(v)) {
|
|
v.foo();
|
|
}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
https://www.typescriptlang.org/docs/handbook/advanced-types.html[TypeScript advanced types]
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Change this boolean return type into a type predicate
|
|
|
|
|
|
=== Highlighting
|
|
|
|
The function declaration
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 14 Nov 2017, 21:23:12 Ann Campbell wrote:
|
|
\[~jeanchristophe.collet] from this description I don't understand what type guards do, and from the examples, I have no idea how they work.
|
|
|
|
endif::env-github,rspecator-view[]
|