org.sonar.l10n.javascript.rules.javascript.S4204.html Maven / Gradle / Ivy
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
.
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.
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