make partial type accept null values for undefined fields in typescript

To make a partial type accept null values for undefined fields in TypeScript, we can use the Partial utility type and union it with null. Here is an example:

index.ts
interface MyInterface {
  prop1: string;
  prop2?: number;
}

type MyPartial = Partial<MyInterface> | null;

const myValue: MyPartial = {
  prop2: null
  // prop1 is undefined but that is allowed due to MyPartial
};
216 chars
12 lines

In the example above, we are creating a new type MyPartial which is a union of the Partial utility type on MyInterface and null. This allows us to define the type with optional fields without requiring them to have a value. By allowing null, we can also assign null to any of the properties that are defined in MyInterface.

Note that if we want to allow undefined values as well, we can simply add it to the union:

index.ts
type MyPartial = Partial<MyInterface> | null | undefined;
58 chars
2 lines

This will allow any of the properties to be undefined, null, or missing entirely.

related categories

gistlibby LogSnag