Home > Net >  How can you conditionally tell TypeScript which data type to use?
How can you conditionally tell TypeScript which data type to use?

Time:10-27

I have a situation where a value can return either a string or an object.

The interface is defined as so:

interface RoutesType {
  projects: string | {
    all: string;
    favorite: string;
    critical: string;
  };

And the value is from here:

const routes = {
  projects: include('/projects/', {
    all: '',
    favorite: 'favorite/',
    critical: 'critical/'
  }
};

When I try to access routes.projects.critical, it displays the following error:

Property 'critical' does not exist on type 'string | { all: string; favorite: string; critical: string;}'. 
  Property 'critical' does not exist on type 'string'.

Is there any reasonable way to conditionally tell TS I'm trying to access the object routes.projects and not the string?

CodePudding user response:

You should check the type of the property projects before accessing it:

if (typeof routes.projects !== 'string') {
    // you can now access routes.projects.critical
}
  • Related