Typescript Type Annotations
Learn how to specify types for variables, function parameters, and return values.
In TypeScript, type annotations allow you to specify types for variables, function parameters, and return values, which improves code readability and catches potential errors. Here’s a breakdown of how to use them:
1. Variable Type Annotations
You can define the type of a variable by using a colon (:) followed by the type after the variable name.
In this example:
usernameis astring.ageis anumber.isDeveloperis aboolean.
If you try to assign a different type to these variables, TypeScript will throw an error.
2. Function Parameter Type Annotations
You can specify types for each parameter in a function, ensuring that only the correct types can be passed.
Here:
namemust be astring.agemust be anumber.
If you pass a different type to name or age, TypeScript will give an error.
3. Function Return Type Annotations
You can specify the type of value a function should return by adding a type annotation after the parameter list.
In this example:
The function
addtakes two parameters,aandb, both of typenumber.The return type of
addis also specified asnumber.
If you return a non-number value from this function, TypeScript will throw an error.
4. Optional and Default Parameters
You can mark a parameter as optional by adding a question mark (?) after the parameter name, or provide a default value. Optional parameters have a type of type | undefined.
In greetUser:
titleis optional; if it’s not provided, it will beundefined.
In logMessage:
messagehas a default value and does not require an argument.
By using type annotations, TypeScript ensures you write consistent and reliable code, reducing runtime errors.