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?
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
getDuplicatedArmCount method,Update: Updated the example to contain a method getDuplicatedArmCount to showcase the problem with vanilla TypeScript settings as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With