I have the following code:
type HTTPGet = {
url: string
params?: Record<string, unknown>
result: unknown
}
export const httpGet = <D extends HTTPGet>(url: D['url'], params: D['params'] = undefined): Promise<D['result']> => {
let path = url
if (params !== undefined) {
path += '?' + toHTTPQueryString(params);
}
return fetch(path, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json'
}
})
}
After condition params !== undefined I call toHTTPQueryString, which accepts only Record<string, unknown> type.
But I have the TypeScript error:
TS2345: Argument of type 'D["params"]' is not assignable to parameter of type 'Record<string, unknown>'. Type 'Record<string, unknown> | undefined' is not assignable to type 'Record<string, unknown>'. Type 'undefined' is not assignable to type 'Record<string, unknown>'.
Why I get this message? TypeScript should understand that I have condition params !== undefined and remains only Record<string, unknown> type, that is assignable to toHTTPQueryString parameter type.
toHTTPQueryString? - Shivam Singla