typescriptvisual-studio-codewebstorm

Why autocomplete stop working in an object with type in TypeScript?


I have a list of routes in one object and want to import it in other file and have autocomplete for object properties.

index.ts

import allRoutes from './routes';

allRoutes.routeHome;

routes.ts

const allRoutes = {
  routeHome: '',
  routePortfolio: 'portfolio'
};

export default allRoutes; 

All works fine. But if I add types to my allRoutes for some typecheking like this:

const allRoutes: {[key: string]:string} = {
  routeHome: '',
  routePortfolio: 'portfolio'
};

or like this:

interface IRoutes {
    [key: string]: string;
}

const allRoutes: IRoutes = {
    routeHome: '',
    routePortfolio: 'portfolio'
};

Everything breaks down

I try this in WebStorm or VSCode. If I add a type for object properties - autocomplete stops working. Why does it happen? And how I can fix this?


Solution

  • Once you initialize the constant with type { [key: string]: string }, the original type is lost. If you want to preserve the original type but check that it is assignable to { [key: string]: string }, you can do this:

    function asStrings<T extends { [key: string]: string }>(arg: T): T {
      return arg;
    }
    
    const allRoutes = asStrings({
      routeHome: '',
      routePortfolio: 'portfolio'
    });
    

    There is a suggestion for a solution that would not require calling a function.