Closed leobastiani closed 8 months ago
This code below should give an error
type MyProps = { a: number };
type IdentityHof = <Props extends {}>(props: Props) => Props;
type ApplyToHof<
Hof extends (props: Props) => any,
Props extends {}
> = Hof extends (props: Props) => infer R ? R : never;
type SameAsMyProps = ApplyToHof<IdentityHof, MyProps>;
const example: SameAsMyProps = {
c: 1
};
Structural inference, which is what's happening here, doesn't perform generic instantiation like would be needed to resolve this. The performance implications of doing that would be, as far as I can imagine, catastrophic.
Ideally, I'd like to be able to transform type IdentityHof = <Props extends {}>(props: Props) => Props;
to type IdentityHofTwo<Props extends {}> = (props: Props) => Props;
. Is it possible?
The main issue here is getting the return of a function like () => <Props extends {}>(props: Props) => Props & { b: number; }
from an input like { a: number; }
and finally getting the result { a: number; b: number; }
.
Although applying ReturnType
to the high-order function in this example returns <Props extends {}>(props: Props) => Props & { b: number; }
Bug Report
🔎 Search Terms
generic type inference, higher-order functions
🕗 Version & Regression Information
This is the behavior in every version I tried, and I reviewed the FAQ for entries about generic type inference and higher-order functions.
⏯ Playground Link
Workbench Repro
💻 Code
🙁 Actual behavior
Error at last line
Type '{ a: number; b: number; }' is not assignable to type '{ b: number; }'. Object literal may only specify known properties, and 'a' does not exist in type '{ b: number; }'.
🙂 Expected behavior
Build successfully