For the below class and interface declaration:
interface NodeConnection<
TListeners extends any = any,
TBroadcasters extends any = any
> {}
class NodeConnection<
TListeners extends any = any,
TBroadcasters extends any = any
> { ... }
I am getting the following typescript error:
class NodeConnection<TListeners extends unknown = any, TBroadcasters extends unknown = any>
interface NodeConnection<TListeners extends unknown = any, TBroadcasters extends unknown = any>
All declarations of 'NodeConnection' must have identical type parameters.ts(2428)
First of, why is typescript thinking that I am trying to extend unknown
instead of the any
type I written, and why does it think that the two type parameters are not identical? How should I solve this issue?
CodePudding user response:
This is because of any
. Since any
can accept any data type, typescript can't assure that the both declaration of NodeConnection would have same type. But, in case you have specific types as follow:
interface NodeConnection<
TListeners extends String,
TBroadcasters extends String
> {}
class NodeConnection<
TListeners extends String,
TBroadcasters extends String
> { }
In this case, typescript is assure that the base type would have atleast functionality of String
. Due to which is allows it.
You can try this at: Typescript Playground
CodePudding user response:
- The interface and the class needs to be different names
- The class should correctly implement the interface, including "passing" the generic parameters
interface INodeConnection<
TListeners extends any = any,
TBroadcasters extends any = any
> {}
class NodeConnection<
TListeners extends any = any,
TBroadcasters extends any = any
> implements INodeConnection<TListeners, TBroadcasters> { }
If you do not plan to use the interface to expose an "interface" to the class that is used in "most places", there is no need for it as the class can use generics without it.
CodePudding user response:
There's no need to both declare an interface and to create a class with exactly that interface. You can simply just create the class and use it as an interface:
class NodeConnection<
TListeners extends any = any,
TBroadcasters extends any = any
> { ... }
class MyNodeConnection implements NodeConnection<MyListeners, MyBroadcasters>
{
...
}
Note that using implements
like this is different from using extends
:
class MyNodeConnection extends NodeConnection<MyListeners, MyBroadcasters>
{
...
}