Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert the type { [k: string]: string; }' to a custom type

So I have a custom type

type urlParamsType = {
    drawer: 'true' | undefined,          
    action: 'edit' | 'create' | undefined,     
}

And I want to use use it in my component:

const MyComponent = () => {
     const { drawer, action}: urlParamsType = useUrlSearchParams();     
}

useUrlSearchParams returns a type of { \[k: string\]: string; } but I want to cast it as urlParamsType. What’s the correct syntax to do that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The error I get from the code above:

Type '{ [k: string]: string; }' is missing the following properties from type 'urlParamsType': drawer, action

>Solution :

There is no guarantee that the URL parameters will actually return that type since a user could manually edit the parameters.

If you don’t care about that, you can assert the type like this:

const MyComponent = () => {
     const { drawer, action} = useUrlSearchParams() as urlParamsType;     
}

This will fully change the type, even if it doesn’t necessarily match. However, be aware that code further down could fail if the parameters are modified to be some other value that you are not expecting.

If you want your code to be truly type-safe, you can use JS to manually validate the data and handle it if it’s invalid. You could do this with a library like Zod which works very well with TypeScript, or you could just do it by hand (eg using typeof).

Side note: typical TypeScript convention is to start type/interface names with an uppercase letter, so you may want to rename it to UrlParamsType or URLParamsType (though not required)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading