Thuta Learning
TypeScript
BasicProgrammingIntermediate

Basic Types

TypeScriptLesson 620 min

What you'll walk away with

  • Declare variables with `string`, `number` and `boolean` annotations
  • Explain that `number` is one type for both integers and decimals, and why `5.0` prints as `5`
  • Predict which type TypeScript infers from an initial value
  • Explain why `any` hides bugs, and avoid it

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.

retries.ts
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 function

What `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.

TypeExample valuesNotes
string"Hello", 'Hi', `Hi ${name}`All three quote styles are strings
number100, 3.14, -7, NaNNo separate integer or float type
booleantrue, falseNot the same as the string "true"
bigint10nWhole numbers too large for number
null / undefinednull, undefinedMark 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.

Where a variable's type comes from
  1. Annotated? Use that type
  2. Otherwise infer from the value
  3. No value either? Annotate it
  4. `any` means checking is off

Once a variable has a type, it keeps that type for its whole lifetime.

General pattern: declaring basic types

typescript
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 it

Write 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)`.

basic-types.ts
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

  1. Three annotated primitiveslet framework: string = "TypeScript";

    Only strings may go into `framework`. `version` and `isAwesome` make the same kind of promise for `number` and `boolean`.

  2. Inferencelet lessons = 28; // no annotation: TypeScript infers number

    There is no annotation, yet `lessons` is a `number`; writing `lessons = "many"` later would be a compile error.

  3. any accepts anythinganything = "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`.

  4. 5.0 prints as 5console.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.

  5. Formatting decimalsconsole.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`.

You should see
Learning TypeScript v5
Learning TypeScript v5.0
number boolean string

How 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`
product-label.ts
// 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 out

Expected: 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
product-label.ts
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

After `let version: number = 5.0;`, what does `console.log("v" + version)` print?

Quick quiz 2 / 3

After `let count = 10;`, what happens when you write `count = "ten";`?

Quick quiz 3 / 3

What happens when `let value: any = 4; value.toUpperCase();` is compiled and run?

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

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Basic Types | Thuta Learning