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
The error I get from the code above:
Type '{ [k: string]: string; }' is missing the following properties from type 'urlParamsType': drawer, action
Jack Pilowsky is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
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)