Answer the question
In order to leave comments, you need to log in
Is using generics with any bad practice?
Let's say there is a generic class
class MyClass<T> {
myMethod(): T {...};
}
class MySecondClass<T> {
constructor(private myInstance: MyClass<T>){};
}
MySecondClass
it doesn't matter what parameter MyClass
. The main thing is that an instance of MyClass
. Question - this problem is solved only with the help any
? Or if there is a generic dependency, then the default class must also be a generic? Is using any in generics a normal practice? any
? Are there parameters everywhere?Answer the question
In order to leave comments, you need to log in
unknown
- perfectly normal, it can be used everywhere where the type is not known. It does not degrade the quality of the code in any way.
any
- it is perfectly normal to use it in generics if it is used for type inference (for example T extends (...args: any) => any)
, to refuse it completely is a witch hunt.
In your case, if the type MyClass
may not be interesting in principle, then it MyClass
should be set in a good way, so that you can write simply constructor(private myInstance: MyClass){};
, i.e. have default types:
class MyClass<T = unknown> {
myMethod(): T {...};
}
unknown
or any
will be already bad practice. However, if there are no alternatives, and the generic is really bad, then what can you do.)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question