As I continue to improve my coding skills with TypeScript, I find myself in the shoes of a full stack developer experienced in C#, an object-oriented programming language. Personally, I have a strong distaste for dynamically typed languages and fortunately, I haven't had to work with any yet.
The issue that has recently dawned on me is the use of "any" casting, especially problematic for beginners and those unfamiliar with OOP concepts. While it's understandable for generic methods like fetching data from various sources such as axios, rxjs, or local storage to return any type of value due to their variable nature, there are instances where improper casting can lead to errors.
For example, the following code snippet is deemed illegal in TypeScript:
class C1 {id: string}
class C2 {num: number}
const c1 = new C1()
const c2: C2 = c1;
In contrast, TypeScript permits the following scenario using the "any" keyword:
class C1 {/*...*/}
class C2 {/*...*/}
const c1 = new C1();
const c2: C2 = c1 as any;
My current project involves numerous instances of such castings, which complicate refactoring and often introduce bugs. It feels haphazard, akin to resorting to "any" casting whenever faced with an error, regardless of consequences.
I'm left wondering if there is a legitimate use case for this feature in TypeScript.
In line with OOP principles, setting specific types when creating generic methods is crucial. Although C# offers the object type as a workaround, it's generally discouraged. Fortunately, TypeScript provides similar functionality:
// C# Example:
public T GenericMethod<T>() {
//...
}
var c1 = GenericMethod<C1>();
// TypeScript Example:
genericMethod<T>() {}
// or even
genericMethod = <T>() => ({} as T);
This standardized approach proves beneficial for interacting with databases, handling data retrieval from various sources, and efficiently managing potential exceptions.