Consider the (simplified) code:
interface GenericInterface<T> { value: T }
function genericIdentity<T>(instance : GenericInterface<T>) : GenericInterface<T> {
return instance;
}
class GenericImplementingClass<T> implements GenericInterface<T> {
value!: T
add() {}
}
let numberInstance = new GenericImplementingClass<number>();
let genericInstance = genericIdentity(numberInstance);
genericInstance.add(); // ERROR: Property 'add' does not exist on type 'GenericInterface<unknown>'.
What is a way to modify the genericIdentity
function so that it can return the specific type including the template parameter?
My attempts:
// attempting to separate the types for derivation and the template type
// ERROR: '?' expected at the ")" - which seems unclear
function genericIdentity<T, DerivedInterface>(instance : DerivedInterface extends GenericInterface<T>) : DerivedInterface {
return instance;
}
// trying to indicate that the type extends the interface
// - VS-Code throws many error messages
function genericIdentity<DerivedInterface<T> extends GenericInterface<T>>(instance : DerivedInterface<T>) : DerivedInterface<T> {
return instance;
}
(I am facing a similar issue with a TreeWalker function defined on a generic tree interface, where I need it to return Tree<T>
instead of TreeInterface<T>
)