Rick
Rick

Reputation: 41

How can I assign null to all properties in a type in TS?

I want to turn type A into type B how can I do it

interface A  {
  a: number;
  b: boolean;
}

type B = NullCheck<xxx>;

----> and get

type B =  {
  a: number | null;
  b: boolean | null;
}

how should I implement NullCheck

Upvotes: 1

Views: 640

Answers (1)

Benjamin
Benjamin

Reputation: 3656

Updated:

I expect to add additional null attributes to each property

Solution:

type NullCheck<T> = {
  [P in keyof T]: T[P] | null;
};

Your original code was correct. And as others have pointed you, you may have set strictNullChecks: false in your tsconfig.json file. With strictNullChecks turned off, TypeScript ignored null and undefined.

Try setting strictNullChecks: true in your tsconfig file.

Upvotes: 2

Related Questions