All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S4204.html Maven / Gradle / Ivy

There is a newer version: 10.17.0.28100
Show newest version

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

  • TypeScript Documentation - unknown
  • TypeScript Documentation - any
  • TypeScript Documentation - Narrowing




© 2015 - 2024 Weber Informatics LLC | Privacy Policy