assisrMatheus
assisrMatheus

Reputation: 475

Is it possible to have an augment/conditional type, that adds `undefined` ONLY to properties that currently are null? (Or vice versa)

I don't have expertise with conditional types so I'm not managing to make it work. But imagine that you have this type:

type MyType = {
  name: number;
  description: string | null;
  title: string | null;
}

And I want to augment it with something like

type OutputType = AugmentType<MyType>;

So that it appends another type, say, undefined ONLY to the keys of a type, say, null.

Appending undefined only to null keys would end up resulting in:

type OutputType = {
  name: number; // Kept intact
  description: string | null | undefined; // Undefined appended
  title: string | null | undefined;  // Undefined appended
}

Typescript version doesn't matter, I'm using the latest version.

Upvotes: 0

Views: 55

Answers (1)

Tim
Tim

Reputation: 2912

Sure, super easy. Only wrinkle is the direction of extends is a bit weird.

type NullOrUndefined<TModel> = { [Key in keyof TModel]: null extends TModel[Key] ? (TModel[Key] | undefined) : TModel[Key] };
type OutputType = NullOrUndefined<MyType>;

Basically make a new remapped type, and if the type of the value at a given key includes null, or in undefined as well.

Upvotes: 3

Related Questions