Skip to content

Optional Properties

von Schappler edited this page Oct 19, 2024 · 1 revision

What are optional properties?

Optional properties are properties declared in our type definitions which may not be necessary on every variable created using a custom type created by us.

Let imagine for example that we are creating a type for a user:

  • All users must have a username
  • All users must have a password
  • Not all uses may want to provide their date of birth, but we need our user type to be read to receive this information if the user provides it.

This small scenario shows us a simple example where the use of optional properties are handy.

Keep in mind that optional porperties just have meaning when we are defining custom types in objects - as one should expect, since properties are the keys on the key-value pair that construct and object.

Also, when we make use of optional properties we need really do think a lot if that specific property should whether or not be optional, since declaring a property as optional reduces drastically our type safety.


Create optional properties in custom types

To create an optional property, all that is required is to add a ? at the front of the property name, before declaring which is the type of this property.

If we use the scenario mentioned before as an example, the optional property "dob" (date of birth) should be declared like in the snippet below:

type User = {
  name: string;
  pass: string;
  dob?: Date;
};

const user1: User = {
  name: 'user1',
  pass: 'pass1',
  dob: new Date('10-10-1990'),
};

const user2: User = {
  name: 'user2',
  pass: 'pass2',
};
Clone this wiki locally