Typescript throws an error when trying to pass a type with optional properties as an indexable type: (Playground)
type Thing = {
thing1?: string
thing2?: string
thing3?: number
}
const thing: Thing = {}
function processObject (obj: { [key: string]: string | number }): string {
/* Generic object handler, not specifically for Thing */
return "test"
}
console.assert(processObject(thing) === "test")
This results in:
Error: Argument of type 'Thing' is not assignable to parameter of type '{ [key: string]: string | number; }'. Property 'thing1' is incompatible with index signature. Type 'string | undefined' is not assignable to type 'string | number'. Type 'undefined' is not assignable to type 'string | number'.
Of course, it works if the argument's type is forcibly made optional:
function processObject (obj: { [key: string]: string | number | undefined }): string {
return "test"
}
I don't see why this is necessary, though. According to TS PR #7029, the indexable type should be compatible with other types that have the same implicit index signature.
Whether or not those properties are optional is irrelevant - that property should simply not be present on the object - right? Why do I have to specify undefined? Is there a better way to be doing this?