Is there anything stopping TypeScript from inferring the type of a function?
Simply put:
const startsWithA = str => str.startsWith('a');
const fruitsThatStartWithA = ['apple', 'banana', 'avocado'].filter(startsWithA);
TypeScript cannot infer that startsWithA is of type (value: string): boolean even though it is only ever used as an argument to filter, and TypeScript already knows exactly what filter accepts.
A more common example in my use is that this type-checks fine and TS knows the type of key and value:
JSON.parse('{"a": 1, "b": 2}', (key, value) => {
if (key === 'a') return value * 2;
return value;
});
But as soon as you do this:
const reviver = (key, value) => {
if (key === 'a') return value * 2;
return value;
};
JSON.parse('{"a": 1, "b": 2}', reviver);
Suddenly TS has no idea what you're trying to do. I used to think that no language can infer function types like this until I found the Rust compiler does exactly that.
This is really frustrating because when you work on a JS-only codebase, inline functions don't need any type annotations to just work, but as soon as you refactor that function out, you're forced to write JSDoc for it, even if that function is local and you only ever use it once.
I couldn't find any issues about this in the TypeScript repo but perhaps I haven't searched well enough.
Posted Nov 28, 2023, 9:53 PM UTC
Typescript does not narrow the types of
anys based on usage as designed.https://github.com/microsoft/TypeScript/issues/34738#issuecomment-546489078
Thank you very much for this, my issue searching skills are pretty rough.
This was also mentioned when they implemented the feature for the Wing language, and the contributors agree that the feature can be costly.
That same comment also mentions a recent experimental JS/TS compiler called Ezno that does have this feature, so that's exciting.