TypeScript Basic Types
TypeScript basic types describe the simple values your variables hold. You add a type annotation with a colon after the name, but in many cases TypeScript infers the type for you.
Primitive Types
The primitive types match JavaScript: string, number, boolean, bigint, symbol, null and undefined. Use the lowercase names, not String or Number.
let title: string = "TypeScript Basics";
let pages: number = 240;
let published: boolean = true;
let big: bigint = 100n;
console.log(title, pages, published, big);
// pages = "many"; // Error: Type 'string' is not assignable to type 'number'.TypeScript Basics 240 true 100n
Type Inference
When you initialize a variable, TypeScript infers its type. Explicit annotations are mostly useful for function parameters and for variables declared without a value. With const, the type is narrowed to the exact literal.
let city = "Lahore"; // inferred: string
const country = "PK"; // inferred: "PK" (literal type)
let count; // implicitly any; avoid this
let total: number; // annotate when there is no initial value
total = 42;
console.log(typeof city, country, total);string PK 42
any vs unknown
any turns off type checking completely, so mistakes slip through. unknown also accepts any value, but forces you to check the type before using it. Prefer unknown for values whose type you do not know yet, like parsed JSON.
let a: any = "hello";
a.toFixed(2); // compiles, but crashes at runtime
let u: unknown = "hello";
// u.toUpperCase(); // Error: 'u' is of type 'unknown'.
if (typeof u === "string") {
console.log(u.toUpperCase()); // OK after the check
}TypeError: a.toFixed is not a function
null and undefined
With strict mode, null and undefined are separate types and cannot be assigned to a string or number. Allow them explicitly with a union, as shown in a later chapter.
let nickname: string | null = null;
nickname = "Sunny";
console.log(nickname.length);
// let age: number = undefined; // Error in strict mode5
void and never
- void: a function returns nothing useful, e.g. function log(msg: string): void
- never: a function never finishes, e.g. it always throws or loops forever
- object: any non-primitive value (rarely used directly)
Frequently asked questions
What is the difference between any and unknown in TypeScript?
any disables type checking for that value. unknown accepts anything too, but you must narrow it with a check before using it, so it stays type safe.
Do I need to annotate every variable in TypeScript?
No. Let TypeScript infer types from initial values. Annotate function parameters, return types of public functions and variables without initial values.
Should I use string or String in TypeScript?
Use lowercase string. String with a capital S is the wrapper object type and is almost never what you want.