Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an object property is nullable

Tags:

typescript

I have the following class, for example:

export class User {
  public name: string | null;
  public birthDate: Date;
}

How can I check, for example, in a component, if name is a nullable property? I can get its type (string) but I can't get any information regardless if it can be nullable or not.

like image 366
Pedro Neto Avatar asked Sep 14 '25 10:09

Pedro Neto


1 Answers

you can do it like this:

type IsUndefinable<T, TypeIfTrue, TypeIfFalse> = undefined extends T
  ? TypeIfTrue
  : TypeIfFalse;

type IsNullable<T, TypeIfTrue, TypeIfFalse> = null extends T
  ? TypeIfTrue
  : TypeIfFalse;

type IsUserNameUndefinable = IsUndefinable<User["name"], true, false>;
type IsUserNameNullable = IsNullable<User["name"], true, false>;
like image 159
Adrian Diaz Avatar answered Sep 17 '25 02:09

Adrian Diaz