After successfully compiling and running my code, I noticed that my Typescript editor is still giving a warning for val
in line 57. You can view the code on the Playground Link.
for (const [key, val] of Object.entries(searchInvocation)) {
encodedParams.push(`${encodeURIComponent(key)}=${encodeURIComponent(val)}`);
}
I'm unsure about how to address this warning. Any suggestions on how to narrow down the issue?
In my understanding, the deconstructed variables key
and val
from searchInvocation should be of type SearchField and string respectively based on the type definition...
type SearchField = "q" | "sitename" | "filetype";
type SearchInvocation = {
[K in SearchField]?: string
}
The error message states...
const val: string | undefined
Argument of type 'string | undefined' is not assignable to parameter of type 'string | number | boolean'.
Type 'undefined' is not assignable to type 'string | number | boolean'.ts(2345)
I am uncertain how it could potentially be undefined.
One possibility might be that the Object matches the structure of the SearchInvocation type but additional key value pairs have been added with unknown contents.
Despite this, I don't receive a similar warning when working with ProxyInvocation type which appears similar but requires implicit guardianship.
If unmanaged keys are the root cause, I am looking for suggestions on implementing runtime guards to filter out undesired keys while traversing through them. This may involve identifying and filtering non-SearchField keys at runtime or imposing stricter constraints on the SearchInvocation type.