U
U
user_of_toster2021-05-21 14:00:33
typescript
user_of_toster, 2021-05-21 14:00:33

Is using generics with any bad practice?

Let's say there is a generic class

class MyClass<T> {
     myMethod(): T {...};
}

Now, if I want to use the MyClass instance as a dependency, I need to specify the type parameter everywhere
class MySecondClass<T> {
     constructor(private myInstance: MyClass<T>){};
}

Etc. The problem is that a class that shouldn't be generic becomes generic because of the generic dependency. (and so on in the chain of dependencies)

There are several questions:
1) Let's say MySecondClassit 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?

2) How do other languages ​​deal with such cases without any? Are there parameters everywhere?

It's just embarrassing that even though a class doesn't care about a generic parameter, you have to parameterize a class that isn't generic by default. And the parameterization of one class causes the parameterization of all classes along the chain of dependencies.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-05-21
@user_of_toster

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 MyClassmay not be interesting in principle, then it MyClassshould 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 {...};
}

If the class does not have default types, then it follows logically that the generic is important for it , and you should not omit it. Here setting unknownor anywill 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 question

Ask a Question

731 491 924 answers to any question