Issue
I have inteface
interface CheckNActSetup<C> {
context: (event: Event) => C;
exec: (context: C) => any[];
}
and the class method:
class Test {
register<C>(item: CheckNActSetup<C>) {
}
}
then I would like to use the metod as follow:
let x = new Test();
x.register({
context: e => ({ value: "A" }),
exec: context => context.value
})
but here 'context' parameter in 'exec' property is >unknow<. I would like the compiler to infer that context type is: { value: string }
when I add following (e: Event) it works:
let x = new Test();
x.register({
context: (e: Event) => ({ value: "A" }),
exec: context => context.value
})
How to get the proper context variable type without adding (e: Event)?
My final goal is to have interface defintion as follow:
interface CheckNActSetup<D, C> {
defs: (event: Event) => D,
context: (defs: D) => C;
exec: (context: C) => any[];
when: ((context: C) => boolean)[]; }
Solution
I checked that your code works fine under TS 4.7 but does not compile under 4.6 with error message Object is of type 'unknown'.
Check TS 4.7 Release Notes: Improved Function Inference in Objects and Methods
TypeScript 4.7 can now perform more granular inferences from functions within objects and arrays. This allows the types of these functions to consistently flow in a left-to-right manner just like for plain arguments.
declare function f<T>(arg: { produce: (n: string) => T, consume: (x: T) => void } ): void; // Works f({ produce: () => "hello", consume: x => x.toLowerCase() }); // Works f({ produce: (n: string) => n, consume: x => x.toLowerCase(), }); // Was an error, now works. f({ produce: n => n, consume: x => x.toLowerCase(), }); // Was an error, now works. f({ produce: function () { return "hello"; }, consume: x => x.toLowerCase(), }); // Was an error, now works. f({ produce() { return "hello" }, consume: x => x.toLowerCase(), });
Inference failed in some of these examples because knowing the type of their produce functions would indirectly request the type of arg before finding a good type for T. TypeScript now gathers functions that could contribute to the inferred type of T and infers from them lazily.
For more information, you can take a look at the specific modifications to our inference process.
Answered By - Lesiak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.