Search code examples
typescript

How do I deal with a parameter that can be a specific type or null


I was just taking an online assessment where I ran into an error stating 'Argument of type 'Date| null' is not assignable to parameter of type 'Date'

This was when I was using this function:

function followingDay(date: Date): Date {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1)
}

I was trying to pass in var3 to the function from an input of this type:

interface User {
  var1: number;
  var2: Date;
  var3: Date | null;
}

When I was doing this I had already placed the function call within an if statement that made sure User.var3!= null

How do I get this error to not come up? I looked around a bunch and couldn't find a solution. This was the only thing I found that looked close but did not work. Overall I was trying to get the millisecond time of that var3 if it was present in the imputed user

var day = (user.var3!= null ? followingDay(user.var3).getTime() : null)

Solution

  • Since you are certain it is non-null (from your if check condition I assume you are), you can use the non-null assertion operator to assert this to Typescript:

    var day = (user.var3 != null ? followingDay(user.var3!).getTime() : null)

    See Non-null assertion operator. [typescriptlang.org]