OK, so Product is an interface, which is kind of like a “type”.
I would suggest looking at a crash course on Typescript video or something to get the basics down.
So i Assume that if the Params in the router for example the “id” does not exist in the products array, it will show undefined.
Yeah, I guess. I don’t know - I’ve never done Angular.
But would typescript not by default set a object that cannot be found to undefined or would it just crash?
TS will not do that unless you tell it to do it. And this:
product: Product | undefined;
warns TS that the value stored in the class member product could be
undefined. In other words it is expecting the possibility of nothing there. And based on what we can see, that will be its starting value:
Will it crash? Not just because of that. Usually TS will give you some errors, telling you that the type of the variable you are trying to assign to that does not match type. Usually you’ll find that out before you run it. Could it crash? I doubt because of that, but if some other part of the code assumes that there is an object there, there might be a null pointer exception or something, but that has nothing to do with Angular or TS, that’s just JS.
what is the point of setting it at undefined anyways
Again, it’s not setting it as
undefined. TS wants your variables typed - that’s kind of the point. This is common in most modern computer languages and some people think that is a weakness of JS - that’s why TS was invented.
It’s not setting it to
undefined, it’s telling TS what types to expect. It’s either going to be type Products or it’s going to be
undefined. That property is not initialized, so that means it will be
undefined until it gets set to a value, presumably a value with type Product.
If you removed the “| undefined” I assume that it would throw an error because something of type Product cannot be
undefined. That’s why it must be of type "Product |
undefined". You might be able to get around that if you initialized it, like:
product: Product = INIT_PRODUCT;
and then manage it so it will always match type Product, but this is a valid approach as well.