DEV Community

Orfeo
Orfeo

Posted on

Making Object Properties Optional

Sometimes, you want to create types in TypeScript where not all properties must be provided. This makes your objects flexible, allowing you to specify only some properties when needed.

This tutorial shows how to define such types with optional properties, using a new CustomProperties example.


Original Type Definition

Here's an example of a type where all properties might be required and explicitly undefined:

export type CustomProperties = {
  language: Language | undefined,
  priority: "high" | "low" | undefined,
  archive: boolean | undefined,
}
Enter fullscreen mode Exit fullscreen mode

This definition means you must always specify the properties, even if their value is undefined.


Making Properties Optional with ?

To allow passing only some properties, mark properties as optional by adding a question mark (?) after the property name:

export type CustomProperties = {
  language?: Language,
  priority?: "high" | "low",
  archive?: boolean,
}
Enter fullscreen mode Exit fullscreen mode

Key Points

  • The ? makes the property optional, so it can be omitted entirely.
  • You do not need to explicitly say | undefined because the property may be absent.
  • When present, the property's value must be one of the specified types.

Examples of Usage

const a: CustomProperties = { language: Language.fr };
const b: CustomProperties = { priority: "high", archive: false };
const c: CustomProperties = { language: Language.en, archive: true };
const d: CustomProperties = {}; // All properties omitted, valid!
Enter fullscreen mode Exit fullscreen mode

Extending or Combining Types

If you need to add optional fields to an existing type, you can use intersection (&):

type BaseProperties = {
  type?: TMediaType,
  email_subject?: string,
  remote_id?: number,
};

export type ExtendedCustomProperties = BaseProperties & {
  language?: Language,
  priority?: "high" | "low",
  archive?: boolean,
};
Enter fullscreen mode Exit fullscreen mode

This composes the base and new properties as optional.


Summary

  • Use ? to mark properties optional in type definitions.
  • Avoid | undefined for optional properties because optionality already allows absence.
  • Optional properties enable flexible object construction with any subset of the property keys.
  • Use intersection types to extend types easily with new optional properties.

References

Top comments (0)