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?
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.
This is what helped me to have autocompletion and prevent typescript from moaning
type TPage = {
id: string;
title: string;
path: string;
};
function asRecord<T extends Record<string, TPage>>(arg: T): T & Record<string, TPage> {
return arg;
}
const EXAMPLES_PAGES = asRecord({
chart2D_basicCharts_BandSeriesChart: {
id: "chart2D_basicCharts_BandSeriesChart",
title: "BandSeriesChart",
path: "/chart2D_basicCharts_BandSeriesChart"
},
chart2D_basicCharts_FanChart: {
id: "chart2D_basicCharts_FanChart",
title: "FanChart",
path: "/chart2D_basicCharts_FanChart"
}
})
const currentExampleKey = Object.keys(EXAMPLES_PAGES).find(key => EXAMPLES_PAGES[key].path === location.pathname);
If you want to type your object without autocomplete loss and keep advantage of readonly you can use as const
const object = {
title: "Autocomplete",
} as const
Logged as WEB-34642, please follow it for updates
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With