Home > other >  How do I narrow down this TypeScript interface?
How do I narrow down this TypeScript interface?

Time:02-14

I have a TypeScript interface like this:

export interface User {
  firstName?: string;
  lastName?: string;
  displayName?: string;
  photoURL?: string;
  email?: string;
  phoneNumber?: string;
  uid: string;
}

And I have a variable that is typed like this:

const user: boolean | User

Now I want to narrow it down using this:

if (typeof user === 'User') {
  //Do some things with the User object that are not possible with a boolean
}

But I am getting this TypeScript error:

This condition will always return 'false' since the types '"string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"' and '"User"' have no overlap. ts(2367)

I have also tried this:

if (user instanceof 'User') {
   //Do some things with the User object that are not possible with a boolean
}

But then it throws this TypeScript error:

The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type. ts(2359)

How do I narrow the variable down for the User type?

CodePudding user response:

The typeof operator evaluates to expressions which include an enumeration of strings, amongst which "User" will never be included.

Reverse your conditional logic:

TS Playground

if (typeof user !== 'boolean') {
  user; // User
}
else {
  user; // boolean
}

While this works for your case, where the discrimination is binary, in the case where more types are possible, you will find that using a type predicate is quite helpful.

  • Related