Optional property declarations should use ‘?’ syntax

Why you should care

In TypeScript there are several ways to declare an optional property, i.e. a property which might be missing from an object: adding “| undefined” in the property type or adding “?” after its name. The latter is preferred as it brings more clarity and readability to a code.

How we detect

CAST Highlight counts one occurrence each time a property is declared optional with ‘| undefined’. This code insight is only for interfaces, because optional property is not allowed for classes.

Bad Code 

interface Person {
  name: string;
  nickname: string | undefined; // Noncompliant
  pet?: Animal | undefined; // Noncompliant, "undefined" is redundant
  age: number;
}

Good Code 

interface Person {
  name: string;
  nickname?: string;
  pet?: Animal;
  age: number;
}

References

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.