Skip to content
This repository has been archived by the owner on Apr 27, 2021. It is now read-only.

Latest commit

 

History

History
26 lines (21 loc) · 643 Bytes

prefer-optional.md

File metadata and controls

26 lines (21 loc) · 643 Bytes

prefer-optional

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.

Noncompliant Code Example

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

Compliant Solution

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