all type attributes optional in typescript

In TypeScript, we can make all the attributes of an interface optional by using the ? symbol after the attribute name.

Here's an example:

index.ts
interface User {
  name?: string;
  email?: string;
  age?: number;
}
70 chars
6 lines

In this example, all three attributes are optional. We can create a User object with any number of attributes, like this:

index.ts
const user1: User = { name: "Alice" };
const user2: User = { name: "Bob", email: "bob@example.com" };
const user3: User = { name: "Charlie", email: "charlie@example.com", age: 30 };
182 chars
4 lines

Note that we can omit any of the attributes when creating a User object.

If we want to require at least one attribute to be present, we can use a union type:

index.ts
interface User {
  name?: string;
  email?: string;
  age?: number;
  [propName: string]: string | number | undefined;
}
121 chars
7 lines

In this example, we added an index signature to allow any string key to have a value of either a string or a number, and made all attributes optional. This allows us to require at least one of the attributes to be present, while still allowing any combination of attributes to be used.

gistlibby LogSnag