I was learning Typescript with React and faced some confusion with why it is important to restrict devs to assign only a certain type or types to a certain variable. Moreover, as I can see, Typescript is about the use of validation on what exact types we can assign to a variable(I hope I am right:)). So, let me explain what I mean, say, we have the following code:
interface Props {
color?: ColorTypes | 'inherit';
variant?: TypographyVariant;
}
Also, TypographyVariant represents this code: export declare type TypographyVariant = 'h0' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'subtitle1' | 'subtitle2' | 'body1' | 'body2' | 'body3' | 'caption';
the question is what is the real benefit of, for example, ensuring that "variant" property only accepts 'h0' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'subtitle1' | 'subtitle2' | 'body1' | 'body2' | 'body3' | 'caption'. The same thing with "color" property. I just cannot explain to myself WHY should we care about validating and ensuring that only certain types can be assigned? and what if we do not assign type annotations to variables. Is it true that if we do not use Type annotations in Typescript then we can assign any value which will not then trigger any error and that error is only found during run-time making us lose time and possibility of not finding that missed error. Is that true?
const props: Props = {color: 'blah'}. Some believe that if you have enough unit tests, you don't need static types because you are making sure all your code paths are covered, but you would need to add type checking in your own code. I prefer to let the compiler do that kind of work. Suggestion, your question should have a single question mark to make it clearer.