I have the following code:
const urls = {
inviteNewUser: ({teamId, intent = 'invite'}: {teamId: string; intent?: Intent}) => `/magic-link?intent=${intent}&teamId=${teamId}`,
resetPassword: ({intent = 'reset-password'}: {intent?: Intent}) => `/magic-link?intent=${intent}`,
} as const
type URLS = typeof urls
type OptionArgs<T extends keyof URLS> = Parameters<URLS[T]>[0]
export function getUrl<T extends keyof URLS>(
key: T,
options: {
args: OptionArgs<T>
} = {
args: {}
},
) {
const urlCreator: URLS[T] = urls[key]
const args = options.args // <- this should be strictly typed according to the key passed in
const url = urlCreator(args) // <- but here I get the error `Property 'teamId' is missing in type '{....`
return url
}
Which throws the following type error:
Argument of type '{ teamId: string; intent?: Intent | undefined; } | { intent?: Intent | undefined; }' is not assignable to parameter of type '{ teamId: string; intent?: Intent | undefined; }'.
Property 'teamId' is missing in type '{ intent?: Intent | undefined; }' but required in type '{ teamId: string; intent?: Intent | undefined; }'
I don't understand why this error happens. To my understanding, it should be clear that URLS[T]
and Parameters<URLS[T]>[0]
should always match. What is the reason that doesn't work, and how can I fix it?