I have succeeded at getting my code to compile and run fine, but my Typescript editor is still reporting a warning for val
in line 57 at Playground Link
for (const [key, val] of Object.entries(searchInvocation)) {
encodedParams.push(`${encodeURIComponent(key)}=${encodeURIComponent(val)}`);
}
I cannot fathom how to eliminate the warning. Can anyone see an obvious change which would give the required narrowing?
I thought the key
and val
destructured from searchInvocation must be a SearchField and string respectively, according to this type specification...
type SearchField = "q" | "sitename" | "filetype";
type SearchInvocation = {
[K in SearchField]?: string
}
The error is reported as...
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)
...but I don't know how it could ever be undefined.
Perhaps it's warning me that the Object could conform to the shape of the SearchInvocation type, but other (unmanaged) key value pairs could have been added on top, and their contents are unknown.
However, I don't get an equivalent warning from traversing Object.entries() from the ProxyInvocation type, which looks somewhat equivalent, but must be implicitly guarded.
If unmanaged keys is the source of the issue, I don't know how to add runtime guards which would filter the keys I am traversing to only the keys managed by the SearchInvocation type. I think that would involve reading the union of string literals listed in SearchField at javascript runtime to filter the others out. Or perhaps I can impose a further limitation on the SearchInvocation type to never accept keys which are not from SearchField.