Explain it simply
Basic types in plain words
In TypeScript you can write a colon and a type after a variable's name, as in `let age: number = 30;`. The three most common types are `string` for text ("Hello"), `number` for numbers (100, 3.14) and `boolean` for yes/no values (`true` or `false`).
Once a variable has a type, a value of a different type cannot go into it. You do not always have to write it, though: with `let age = 30;` TypeScript looks at `30` and works out `number` by itself. One special type is `any`, which allows anything and switches type checking off.
Problem → Why → Solution
The problem: `any` lets a bug reach run time
Say you read a retry count from a config file. The file stores it as the string `"3"`, and the variable is typed `any`. `retries + 1` becomes `"31"`, not `4`.
Because of `any`, the compiler treats `attempts` as `any` too and allows `attempts.toFixed(0)`. Only at run time does it crash with a TypeError, because strings have no `toFixed`. One `any` spreads to every value it touches.
let retries: any = "3"; // read from a config file
const attempts = retries + 1; // "31" - attempts is any too
console.log(attempts.toFixed(0)); // TypeError: attempts.toFixed is not a functionWhat `number` would have done
With `let retries: number = "3";` the compiler immediately reports 'Type string is not assignable to type number'. The warning moves from the line that crashes to the line where the data enters, which is exactly where you should convert it with `Number(...)`. `any` throws that warning away.
Core concept: primitive types, inference and any
For each kind of basic JavaScript value (a primitive), TypeScript has a matching type written in lowercase. Besides the three main ones in this lesson, the table collects the rest so you can recognize them. You will use `string`, `number` and `boolean` constantly; `bigint` and `symbol` (not shown) are rare in everyday application code.
| Type | Example values | Notes |
|---|---|---|
| string | "Hello", 'Hi', `Hi ${name}` | All three quote styles are strings |
| number | 100, 3.14, -7, NaN | No separate integer or float type |
| boolean | true, false | Not the same as the string "true" |
| bigint | 10n | Whole numbers too large for number |
| null / undefined | null, undefined | Mark the absence of a value |
`number` has no separate integer type. `5`, `5.0` and `5.00` are one and the same value, and printing any of them shows `5`. To show a fixed number of decimals, format it into a string with a method such as `toFixed(1)`. Likewise, `NaN` ('not a number') is itself of type `number`, so a failed conversion like `Number("abc")` still type-checks; you must test for it with `Number.isNaN`.
Thanks to inference, most annotations can be left out. With `let title = "Basic Types"`, `title` is a `string` and a later `title = 42` is an error. Write annotations for variables declared without a value and for function parameters.
`any` means 'do not check this variable'. Any value can go in, any method can be called, and the results become `any` as well. It can serve as a temporary step while converting old JavaScript, but it does not belong in new code. When you genuinely do not know a value's type, the safer `unknown`, covered in the next lesson, is the right tool.
- Annotated? Use that type
- Otherwise infer from the value
- No value either? Annotate it
- `any` means checking is off
Once a variable has a type, it keeps that type for its whole lifetime.
General pattern: declaring basic types
let textName: string = "text";
let numberName: number = 0;
let flagName: boolean = false;
let inferredName = "value"; // type comes from the value
let laterName: number; // no value yet: annotate itWrite type names in lowercase (`string`, not `String`). When there is an initial value, you can leave the annotation out and let TypeScript infer it.
Basic types in action
This example puts the three basic types, inference and `any` side by side. Look closely at the version number: the code stores `5.0` as a `number`, and JavaScript prints it as `5`, so the output shows the result both before and after formatting it with `toFixed(1)`.
let framework: string = "TypeScript";
let version: number = 5.0; // 5.0 and 5 are the same number
let isAwesome: boolean = true;
let lessons = 28; // no annotation: TypeScript infers number
// 'any' switches type checking off for this variable
let anything: any = 4;
anything = "Now I'm a string";
console.log(`Learning ${framework} v${version}`);
console.log(`Learning ${framework} v${version.toFixed(1)}`);
console.log(typeof lessons, typeof isAwesome, typeof anything);Code breakdown
- Three annotated primitives
let framework: string = "TypeScript";Only strings may go into `framework`. `version` and `isAwesome` make the same kind of promise for `number` and `boolean`.
- Inference
let lessons = 28; // no annotation: TypeScript infers numberThere is no annotation, yet `lessons` is a `number`; writing `lessons = "many"` later would be a compile error.
- any accepts anything
anything = "Now I'm a string";`anything` starts as a number but accepts a string afterwards, because the compiler no longer checks it. The last line shows `typeof anything` is now `string`.
- 5.0 prints as 5
console.log(`Learning ${framework} v${version}`);`version` simply holds the number `5`, so this prints `Learning TypeScript v5`. Writing `5.0` in the source does not change the value.
- Formatting decimals
console.log(`Learning ${framework} v${version.toFixed(1)}`);`toFixed(1)` returns the string `"5.0"`, so this prints `Learning TypeScript v5.0`. The editor offers `toFixed` because it knows `version` is a `number`.
Learning TypeScript v5
Learning TypeScript v5.0
number boolean stringHow inference differs for `let` and `const`
With `let mode = "dark";` the type of `mode` is `string`, because a `let` variable may later be set to another string. With `const mode = "dark";` the value can never change, so TypeScript records the more precise type `"dark"`, a type with exactly one value. This is called a literal type, and the Literal Types lesson covers it in detail.
Hover over a variable name in your editor to see the type TypeScript inferred. Write both the `let` and the `const` version and compare them yourself.
In real projects
Basic types in real projects
Most data in real code is ultimately made of basic types: a user's email is a `string`, prices and quantities are `number`s, and flags such as `isAdmin` or `emailVerified` are `boolean`s. When you meet interfaces and object types in later lessons, the type of each field will be one of the primitives from this lesson.
When storing money as a `number`, many projects avoid floating-point surprises like `0.1 + 0.2` giving `0.30000000000000004` by storing whole cents (350 rather than 3.5) and formatting with `toFixed(2)` only for display. Teams also often enable ESLint's `no-explicit-any` rule, so every new `any` has to be justified in code review before it can be merged.
Common mistakes
Common basic-type mistakes
Using uppercase `String` or `Number`
`String`, `Number` and `Boolean` refer to JavaScript's wrapper objects, not the primitive types. `let name: String` appears to work, but the TypeScript docs themselves advise against it. Always use lowercase `string`, `number` and `boolean`.
Expecting `5.0` to print as a decimal
It is easy to write `5.0` in the code and expect `v5.0` in the output, but running it prints `v5`. A `number` does not remember how many decimals you typed. If a value such as a version is really text to display, store it as a `string` ("5.0"), or format it with `toFixed` when you print it.
Adding `any` to make an error go away
`any` does not fix an error; it blindfolds the compiler, and the bug travels to run time as in the problem. Convert the value to the right type (`Number("3")`), or use `unknown` when the type is genuinely unknown.
Best practices
Good habits with basic types
- Rely on inference for local variables that start with a value
- Convert outside strings with `Number()` and check them with `Number.isNaN` before use
- In new code, choose a real type or `unknown` instead of `any`
Mini challenge
Mini challenge: a product label
Declare a product's name, price and stock status with basic types, and write a function that produces a label such as `Notebook - $3.50 - in stock`.
- Write `productLabel(name: string, price: number, inStock: boolean): string`
- Show the price with two decimals (`3.50`), even when it is `3.5`
- Show `sold out` when `inStock` is false
- Do not use `any`
// TODO: declare a name (string), a price (number) and inStock (boolean)
function productLabel(name: string, price: number, inStock: boolean): string {
// TODO: format the price with two decimals
// TODO: pick "in stock" or "sold out"
// TODO: return "<name> - $<price> - <status>"
}
// TODO: print a label for your product and for one that is sold outExpected: Prints `Notebook - $3.50 - in stock` and `Pen - $1.25 - sold out`.
Show hint
Combine `price.toFixed(2)` with the ternary `inStock ? "in stock" : "sold out"`.
Show solution
const productName: string = "Notebook";
const productPrice: number = 3.5;
const available: boolean = true;
function productLabel(name: string, price: number, inStock: boolean): string {
const status = inStock ? "in stock" : "sold out";
return `${name} - $${price.toFixed(2)} - ${status}`;
}
console.log(productLabel(productName, productPrice, available));
console.log(productLabel("Pen", 1.25, false));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Three basic types: `string` (text), `number` (integers and decimals), `boolean` (true/false)
- The annotation shape is `let name: type = value;`, with lowercase type names
- With an initial value, TypeScript infers the type for you
- `5.0` prints as `5`; use `toFixed` when you need decimals
- `any` turns checking off and spreads, so avoid it
TypeScript Handbook — TypeScript