Real-world TypeScript development
Learn TypeScript basic data types with clear explanations and practical examples. This tutorial covers string, number, boolean, null, undefined, any, unknown, void, and never for real-world TypeScript development.
1. String
The string type is used to represent textual data. In TypeScript, strings can be defined using single quotes, double quotes, or template literals.
Example
Strings ensure that only text values are assigned, preventing accidental assignment of numbers or objects.
2. Number
The number type represents both integer and floating-point values. TypeScript does not differentiate between int and float.
Example
Any attempt to assign a non-numeric value will result in a compilation error.
3. Boolean
The boolean type represents logical values: true or false.
Example
Booleans are commonly used in conditions, flags, and feature toggles.
4. Null and Undefined
null and undefined represent absence of value.
undefinedmeans a variable is declared but not assigned.nullmeans a variable is explicitly set to have no value.
Example
With strict null checks enabled, null and undefined must be handled explicitly.
Example with Strict Mode
5. Any and Unknown
Any
The any type disables type checking. It allows assigning any value and calling any method.
Example
Using any removes TypeScript’s safety and should be avoided in production code.
Unknown
The unknown type is safer than any. You must perform type checks before using the value.
Example
unknown is recommended when dealing with external data such as API responses.
6. Void and Never
Void
The void type is used for functions that do not return any value.
Example
Never
The never type represents values that never occur. It is commonly used for functions that always throw errors or never complete.
Example
Another example is an infinite loop:
Conclusion
Understanding basic data types is fundamental to mastering TypeScript. Strong typing improves code safety, readability, and maintainability. Choosing the correct data type helps prevent bugs and ensures predictable behavior in real-world applications.