60 lines
2.0 KiB
Plaintext
60 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
In TypeScript, `any` is a type that is used when the type of a variable is unknown or could be of any type. It allows you to opt-out of type-checking and let the values pass through compile-time checks. In other words, it prevents the compiler from reporting type errors, which can lead to runtime errors.
|
|
|
|
On the other hand, `unknown` is a type-safe alternative to `any`. It forces you to perform certain checks before performing operations on variables of type `unknown`. This means you can't accidentally perform arbitrary operations on variables of type `unknown`, which helps prevent runtime errors.
|
|
|
|
It's generally recommended to avoid using `any` when possible, and instead use more specific types or generics for better type safety. If you want to maintain type safety, it's better to use `unknown` instead of `any`.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
function logValue(value: any) { // Noncompliant: 'value' is not type-checked
|
|
console.log(value);
|
|
}
|
|
|
|
logValue(123);
|
|
logValue('Hello');
|
|
----
|
|
|
|
You should use `unknown` instead of `any` and narrow it down with type guards.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
function logValue(value: unknown) {
|
|
if (typeof value === 'number') {
|
|
console.log(value.toFixed(2));
|
|
} else if (typeof value === 'string') {
|
|
console.log(value.trim());
|
|
}
|
|
}
|
|
|
|
logValue(123);
|
|
logValue('Hello');
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown[`unknown`]
|
|
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any[`any`]
|
|
* TypeScript Documentation - https://www.typescriptlang.org/docs/handbook/2/narrowing.html[Narrowing]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
* Remove this use of "any" so that implicit typing will be used.
|
|
* Replace "any" with a specific type.
|
|
|
|
|
|
=== Highlighting
|
|
|
|
``++any++``
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|