Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Difference Between Generic call and .. as Casting in Angular/Typescipt? Especially for HttpClient

I have the Following issue.

Some more expirienced programmers told me to never use generics in http Methods:


public getAll(): Observable<User[]> {
    return this.http.get<User[]>(url);
}

And that I should always use:


public getAll(): Observable<User[]> {
    return this.http.get(url) as Observable<User[]>;
}

No one can explain why. Its a convention(?), but it is hard to grasp why. Is there any "historical meaning" or is it just for reability?

like image 637
Luxusproblem Avatar asked Dec 10 '25 20:12

Luxusproblem


1 Answers

Although at first sight it might seem like these two notations do the same thing, it's not actually true. By generally type-casting expressions like in your second example, you actually weaken the compiler and might miss type errors that you'd otherwise see.

An example:

function copy<T>(object: T): T {
    return {
        ...object
    };
}

class Car {
    armCount = 2;
    wheelCount = 4;
}

class Human {
    armCount = 2;
    wheelCount = 2;

    getDuplicatedArmCount() {
        return this.armCount * 2;
    }
}

const car = new Car();

const carCopy = copy<Car>(car); // 1
const humanCopy = copy<Human>(car); // 2
const humanCopyAndCast = copy(car) as Human; // 3

console.log(humanCopy.getDuplicatedArmCount());
console.log(humanCopyAndCast.getDuplicatedArmCount()); // 4

This is a function that (poorly) copys an object. Obviously, when copying something, the result will be of the same type as the original. That's what the generic definition of T says.

Now when you compile this code, you'll see that

  • 1) is just fine,
  • 2) gives a compiler error as you're trying to copy a car, but expect a human at the end, with a getDuplicatedArmCount method,
  • but with 3), by basically telling the compiler you're more clever than it, you don't get that error while compiling and will have a run-time issue instead in 4) that could easily be avoided.

Update: Updated the example to contain a method getDuplicatedArmCount to showcase the problem with vanilla TypeScript settings as well.

like image 169
fjc Avatar answered Dec 13 '25 08:12

fjc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!