7. Basic Types in TypeScript
Defining Your Data
To benefit from TypeScript, you must tell the compiler what type of data your variables are allowed to hold. This is called Type Annotation. We start with the primitive types: strings, numbers, and booleans.
The Primitives
You apply a type to a variable using a colon : followed by the type name.
Type Inference
TypeScript is incredibly smart. If you assign a value to a variable immediately when you create it, you do not need to write the explicit type annotation. TypeScript will infer (guess correctly) what the type is and protect it just as strictly.
null and undefined
In JavaScript, `null` represents the intentional absence of an object value, while `undefined` means a variable has been declared but not assigned a value. TypeScript treats these as their own specific types.
The 'any' Type: The Escape Hatch
The any type completely turns off the TypeScript compiler for that specific variable. It tells TS, "Let me do whatever I want, act like regular JavaScript." You should avoid `any` at all costs. Using it defeats the entire purpose of installing TypeScript.
The 'unknown' Type: The Safe Escape Hatch
If you genuinely do not know what type of data is coming (e.g., from a third-party API), use unknown instead of any. While unknown allows you to assign any value to it, it strictly forbids you from performing any operations on it until you explicitly prove what type it is.
Knowledge Check
Ready to test your understanding of 7. Basic Types in TypeScript?