Optional-Properties-In-Ts-Objects

Optional Properties in TS objects

Source

When creating objects in TS you can set properties to be optional properties.

So if you have an object which might have or might not have a property, for example a middle name in a user object, you can make one of the properties optional using the ? operator in the key decalration.

Example

interface User {
	id: string;
  firstName: string;
  middleName?: string;
  lastName: string;
}

const admin: User = {
  id: "123",
  firstName: "Foo",
  lastName: "Bar",
};

console.log(admin);

// Prints
{
  firstName: "Foo",
  id: "123",
  lastName: "Bar"
}

#JavaScript
#TypeScript