I would like to generate a type with the exact names of the RoutesPath.
So, the intention is to have a type with these values:
// type RoutesPath --> 'institutions' | 'credentials' | 'token'
But right now, I could only generate the generic type 'string' (type RoutesPath --> string
).
Would that be possible?
type RoutesPath = typeof routes[number]['children'][number]['path']
const routes = [
{
path: '/:token',
component: PLayout,
children: [
{
path: 'institutions',
name: 'display_information',
component: InstitutionsView
},
{
path: 'credentials',
name: 'display_credentials',
component: CredentialsView
},
{
path: 'token',
name: 'display_token',
component: TokenView
}
]
}
]
CodePudding user response:
Yes, It is possible to achieve your goal using "const assertion"
// type RoutesPath --> 'institutions' | 'credentials' | 'token'
Check this :
type RoutesPath = typeof routes[number]["children"][number]["path"];
const routes = [
{
path: "/:token",
component: "x",
children: [
{
path: "institutions",
name: "display_information",
component: "x",
},
{
path: "credentials",
name: "display_credentials",
component: "x",
},
{
path: "token",
name: "display_token",
component: "x",
},
],
},
] as const;
Reason :
If you don't use this assertion, the TS compiler will infer type as string of "RoutesPath" , you can do const assertion and it will infer it as literal type.
Note: You can do something like below if you don't want all to be literal types or readonly properties.
const example = {
align: "left" as const,
padding: 0,
};
So, inferred type will be :
type example = {
align : "left",
padding : number,
}
If you use it like below, everything will considered literal.
const example = {
align: "left",
padding: 0,
} as const;
The inferred type will be :
type example = {
align : "left",
padding : 0,
}
Hope it helps