Imagine having the following interface definitions:
interface SomeInterface {a: string; b: number}
interface SomeFunction<T> {(arg: T) :T}
The usage of the function interface can be demonstrated like this:
const myFun: SomeFunction<string> = arg => arg;
An issue arises when specifying the generic type T
as a string, making it less generic.
The goal is to keep the type T
generic while constraining it.
If we declare the SomeFunction
like this:
interface SomeFunction {<T>(arg: T) : T}
it allows for generic use such as:
const myFun: SomeFunction = (arg) => arg;
However, this approach forfeits the opportunity to constrain T
at the function declaration.
The objective is to have functions that implement SomeFunction
specify that T
must extend
SomeInterface</code and another function require <code>T
to extend something else.
This desired functionality can be achieved with declarations similar to the following:
function myFun2<T extends SomeInterface>(arg: T): T {
console.log(arg.a);
return arg;
}
function myFun3<T extends {c: string }>(arg: T): T {
console.log(arg.c);
return arg;
}
The challenge remains in these declarations not explicitly referencing the SomeFunction
interface, although essentially matching its structure.
Is there an improved method to declare myFun2
and myFun3
to ensure conformity to SomeFunction
?