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: undefined
.
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.