UI.dev - Typing Function Declarations Flashcards
How do we add Type annotations to function parameters?
Similar to how we type variables - just a colon and the type:
What’s the added benefit of adding types to our function parameters?
If our parameters are typed, Typescript can infer the type of the return.
What’s the catch if annotating function parameters on an arrow function?
When using Types, you need to have your parameters within parentheses, even if there is only one parameter. You can’t do the arrow function one param trick.
What’s wrong with this function declaration?
Destructuring syntax already says that a colon with something following it renames the parameter - in the example given, you’d be aliasing the name param as a variable named string.
Instead, to annotate an object, we have to annotate it as an object.
What’s important to remember when annotating object parameters sent to a function?
TypeScript only cares about the properties that it uses inside of the function - so even though an object may have 10 properties, if we only use one within the function, that’s the only one we need to annotate:
How do we annotate function return types in TypeScript?
With a colon after the param list and then the return type:
Why be explicit about a function’s return type if it can usually infer what we’ll be returning?
- It’s useful when writing our functions. If it returns the wrong thing by accident, we find out right away instead of only finding out when we try to use the function elsewhere.
What is the special syntax for annotating the type of a promise?
You put the type of the promise in pointy bois after the Promise declaration.
How do you annotate a function with a callback?
You add parentheses and a parameeter that looks similar to an arrow function - in the parentheses you type the arguments you want, and in the return you put the type that you expect returned.
Do we have to annotate every param of a function even when it’s undefined?
Yessir. That’s what the TypeScript Gods expect.
How do you tell TypeScript that a param is optional?
You just put a ? after the annotation.
Besides adding a question mark after a param, what’s another way to make a parameter optional?
With a default value - this tells TypeScript that the type of the parameter is the type of the default value.
How can you provide types if you don’t know how many parameters will be passed to a function?
Use the rest syntax to get all the parameters in a list. If all of the extra params are the same type, we can easily add an annotation by typing the …rest.
Walk me through this typed function:
After you declare the function, then you declare your arguments (adding types). This includes a callback function, you type this by adding a param and its type after the name of the function, then an arrow, then the return type to be expected.