skip to Main Content

How can I check whether the properties of the object in TypeScript are nullable in a simple way? For example

export default interface UserDto{
     ID?:int;

      USER_NAME?:string;
  
      FIRST_NAME?:string;
  
      LAST_NAME?:string;
  
      USER_ROLE?:string;
  
       TEAM?:string;
     IS_ACTIVE?:Boolean;
    CREATE_DATI?:DateTime;
     UPDATE_DATI?:DateTime;
       PASSWORD?:string;
}

The USER_ROLE property here is nullable. How can I return this to me as nullable or not in an if query

2

Answers


  1. If i understand correctly, you would like to write an if statement that check if the property of an object is optionnal (so not necessary undefined, but defined as optionnal in the type declaration)

    It is not possible, because types doesn’t exists at runtime.

    All you can do is to check the value, or hardcode the name of the keys that are optionnal and use that in your condition.

    Login or Signup to reply.
  2. At runtime this is not possible because all types are removed when compiled (See "What is type erasure?").

    But you can work with the interface at compile time using Conditional Types to check whether a UserDto key is optional or not.

    interface UserDto {
      USER_ROLE?: string;
      REQUIRED: string;
    }
    
    type IsOptionalKey<T, K extends keyof T> = {} extends Pick<T, K>
      ? true
      : false;
    
    type Result = IsOptionalKey<UserDto, "USER_ROLE">; // true
    type Result2 = IsOptionalKey<UserDto, "REQUIRED">; // false
    

    TypeScript Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search