I mentioned adding 'svelte' to the topic prop's union type in the LanguagePillProps interface in our LanguagePill component should resolve the issue. Narrator, it did.
Having to add 'svelte' to the topic props type resolved the issue, but it was extra work. Typically, you want to infer types as much as possible.
Just a note. This is not criticizing Brittney’s pull request (PR). This post is about a potential refactoring I noticed while reviewing her PR which could improve the types' maintenance in the project.
Aside from the type being inferred, the type is now data-driven. If we want to add a new language to the interests array, all places where the InterestType are used now have that new language available. If there is some code that requires all the values in that union type to be used, TypeScript will complain.
In fact, a new issue was opened today because an SVG for Svelte was missing in another part of the application.
We’re on the infer types hype and set up a new piece of state in our React application. We’re going to have a name that can get updated. Somewhere in the application, we call setName(someNameVariable) and all of a sudden, TypeScript is like nope! What happened? The type that gets inferred for
is undefined, so we can’t set a name to a string type. This is where an explicit type is practical.
For return types in functions, there are definitely two camps. Some think that return types should always be explicitly typed even if they can be inferred, and others not so much. I tend to lean towards inference for function return types, but agree with Matt Pocock's take that if you have branching in your function, e.g. if/else, switch, an explicit return type is preferred. More on that in Matt's video.
As mentioned, inferred types are the way to go for most cases, but Kyle Shevlin (@kyleshevlin) messaged me after this blog post went out with another use case to explicitly type the return type.
If a function returns a tuple, you need to explicitly type the return type. Otherwise, the inferred return type will be an array whose items have the union type of all the array items returned.