Home > Back-end >  TypeScript Function Return Type : What does "obj is Date" mean?
TypeScript Function Return Type : What does "obj is Date" mean?

Time:08-18

I just saw this TypeScript Code Snippet

export function is_date(obj: any): obj is Date {
    return Object.prototype.toString.call(obj) === '[object Date]';
}

where I don't understand what obj is Date is doing in the function's "return type".

Appreciate if anyone can explain it

CodePudding user response:

Same as boolean

export function is_date(obj: any): boolean {
    return Object.prototype.toString.call(obj) === '[object Date]';
}

Read docs about (type-guards) https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

CodePudding user response:

It is similar to boolean but it also restricts the type after the function call :

type DateOrString = string | Date

function isDate(dateOrString: DateOrString): dateOrString is Date {
  return date instanceof Date
}

Now if you use it in a conditionnal, you get the variable with the restricted type :

if(isDate(dateOrString)) {
  // here `dateOrString` is of type Date
}
  • Related