๐ง๐๐ฝ๐ฒ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐ง๐๐ฝ๐ฒ ๐๐ป๐ป๐ผ๐๐ฎ๐๐ถ๐ผ๐ป๐ ๐๐๐ถ๐ฑ๐ฒ
Type annotations tell TypeScript what type of value a variable holds.
You use a colon after the name. Example: let age: number = 30.
These labels catch bugs during development.
Use these patterns:
- Variables: let name: string
- Constants: const title: string = "Admin"
- Arrays: let tags: string[]
- Objects: let user: { name: string }
Functions need annotations most. Example: function greet(name: string): void
Void means the function returns nothing.
Use the pipe symbol for multiple types. Example: let id: string | number
TypeScript removes all annotations during compilation. Your final JavaScript code is clean. This means zero runtime cost.
Write annotations when:
- You declare a variable without a value.
- The function return type is not clear.
- You want your team to understand the code faster.
Skip them when:
- The value makes the type obvious.
- TypeScript already knows the type.
Avoid these mistakes:
- Do not use uppercase String or Number. Use lowercase string or number.
- Do not forget return types on public functions.
- Do not annotate when TypeScript already knows the type.