Currently, I am attempting to create a method that includes a parameter with a generic type. In this case, I have used 'unknown' as the generic type since it is not needed:
function f(op: Operation<unknown>): void {...}
. However, this approach does not work in all scenarios, especially if the Operation class uses its generic type in a method signature.
Interestingly, when I directly utilize a generic Context member instead of incorporating it in a method's parameter, the code compiles without any errors.
I am seeking insights into why I am encountering issues using 'unknown' when the generic type is part of a method's signature.
The following example illustrates the problem:
export interface Operation<Context> {
process: (context: Context) => void;
//context: Context;
n: number;
}
type MyContext = {
info: string;
}
const op : Operation<MyContext> = {
process: (context: MyContext) => { console.log("process", context.info); },
//context: {info:"context.info"},
n: 42
}
function fGeneric<Context>(op: Operation<Context>): void {
console.log("fGeneric", op.n);
}
console.log(fGeneric(op));
function fUnknown(op: Operation<unknown>): void {
console.log("fUnknown", op.n);
}
console.log(fUnknown(op));
// Argument of type 'Operation<MyContext>' is not assignable to parameter of type 'Operation<unknown>'.
// Type 'unknown' is not assignable to type 'MyContext'.
If 'process' is commented out and 'context' is uncommented, the code compiles without any error.
(Note: This example has been simplified to highlight the issue at hand.)