While refactoring parts of our React app in TypeScript, I encountered a challenge that required me to use what I consider to be a less than ideal double type argument. I'm unsure if this is a bug in TypeScript or if there is some type ambiguity causing the callback parameter to default to type 'any'.
To address this issue, I had to conceal the original type within another type argument to correct the inference of the wrong type for the callback method due to the "extends string" condition.
Here is the original code snippet:
type Optional<TItem> = TItem extends string
? { get?: (item: TItem) => string }
: { get: (item: TItem) => string };
type TItem = { hello: string } | string;
const obj: Optional<TItem> = {
get: item => typeof item === 'string' ? item : item.hello
};
The error output from npx tsc
with the original code using TypeScript 5.4.2 was:
error TS7006: Parameter 'item' implicitly has an 'any' type.
18 get: item => typeof item === 'string' ? item : item.hello
Below is the workaround applied:
type TItem = { hello: string } | string;
type Optional<TItem, TItemType> = TItemType extends string
? { get?: (item: TItem) => string }
: { get: (item: TItem) => string };
const obj: Optional<TItem, TItem> = {
get: item => typeof item === 'string' ? item : item.hello
};