# Basic Types & Annotations

> What are the basic types in TypeScript? Explain the difference between explicit type annotations and type inference, and when you should write annotations...

Canonical: https://www.internhack.in/learn/interview/typescript-interview/ts-basic-types
Last updated: 2026-11-28

Difficulty: Beginner

## Question

What are the basic types in TypeScript? Explain the difference between explicit type annotations and type inference, and when you should write annotations yourself.

## Answer

TypeScript's basic types mirror JavaScript's values: `string`, `number`, `boolean`, `bigint`, `symbol`, `null`, `undefined`, plus `object`, arrays, and special types like `any`, `unknown`, `void` and `never`. You can annotate a variable explicitly (`let count: number = 0`), but most of the time TypeScript infers the type from the value, so `let count = 0` is already `number`. Good TypeScript code annotates function boundaries and lets inference handle the rest.

### The primitive and special types

| Type | Example | Note |
| --- | --- | --- |
| `string` | `"Swiggy"` | Use lowercase; `String` is the wrapper object type |
| `number` | `499`, `0.1` | One type for ints and floats (IEEE 754 double) |
| `bigint` | `10n` | Arbitrary precision integers, needs target ES2020+ |
| `boolean` | `true` |  |
| `symbol` | `Symbol("id")` | `unique symbol` for const declarations |
| `null`, `undefined` |  | Separate types under `strictNullChecks` |
| `void` | function return | "Return value is not meaningful" |
| `never` | function that always throws | No value can have this type |
| `unknown` / `any` |  | Safe top type vs opt-out of checking |

### How inference works

TypeScript infers from initialisers, return statements, default parameters and contextual position. `const total = 499` gets the literal type `499` because a `const` cannot change, while `let total = 499` is widened to `number`. Callback parameters are inferred contextually: in `orders.map(o => o.id)`, `o` is already typed from the array. Function return types are inferred from the `return` statements.

### When to write annotations

- **Function parameters**: always, since TypeScript does not infer them from usage (they become implicit `any`, which `noImplicitAny` flags).
- **Exported function return types**: optional, but writing them stabilises a module's public API and speeds up type checking. Also required by `isolatedDeclarations` (TS 5.5+).
- **Empty initial values**: `let items: Order[] = []` or `useState<User | null>(null)`, because there is nothing to infer from.
- **Not needed**: `const name: string = "Asha"` is noise. Let inference do it.

### void vs undefined

`void` as a return type means callers should ignore the value. A callback typed `() => void` may actually return something (that is why `arr.forEach(x => list.push(x))` is allowed even though `push` returns a number). `undefined` is a real value type: a function returning `undefined` must actually return it (TS 5.1+ allows omitting the return statement).

### Common mistakes

- Using `Number`, `String`, `Boolean` (wrapper objects) instead of lowercase primitives.
- Annotating everything, which hides better inferred types like literal unions.
- Assuming `number` can safely hold money as rupees with decimals; store paise as integers or use `bigint` for very large values.

**How TypeScript decides a variable's type. Annotations win; otherwise the compiler infers from the value and context.**

1. **Explicit annotation present?**: If yes, that type is used and the value is checked against it.
2. **Infer from the initialiser**: let x = 0 becomes number.
3. **Apply widening rules**: const keeps literal 0, let widens to number.
4. **Use contextual typing**: Callback params get types from where they are passed.
5. **Fall back to implicit any**: Flagged as an error under noImplicitAny.

## Code examples

### Annotations vs inference

```
// Inferred, no annotation needed
let city = "Bengaluru";   // string
const gst = 18;           // literal type 18
let isOpen = true;        // boolean
const big = 9007199254740993n; // bigint

// Annotate when there is nothing to infer from
let cart: string[] = [];
let selected: number | null = null;

// Annotate parameters; return type is inferred as number
function addGst(pricePaise: number, rate = gst) {
  return Math.round(pricePaise * (1 + rate / 100));
}

// Contextual typing: o is inferred from the array
const orders = [{ id: "a1", amountPaise: 1200 }];
const ids = orders.map((o) => o.id); // string[]
```

Only the empty array, the nullable variable and the function parameter need annotations. Everything else is inferred precisely.

### void, undefined and never

```
function logEvent(name: string): void {
  console.log(name);
}

function fail(message: string): never {
  throw new Error(message);
}

// A () => void callback may return a value; it is ignored
const list: number[] = [];
[1, 2, 3].forEach((n) => list.push(n)); // push returns number, still OK

function parseRate(input: string): number {
  const n = Number(input);
  if (Number.isNaN(n)) fail(`Invalid rate: ${input}`);
  return n; // n is number; fail() never returns
}
```

void says the result is irrelevant, never says the function cannot return normally, and control flow analysis uses never to know code after fail() is unreachable.

## Key points

- Use lowercase primitive types, never the String, Number or Boolean wrapper types.
- const declarations get literal types; let declarations widen.
- Annotate parameters and empty initial values; let inference handle the rest.
- void means ignore the return value; never means no normal return.
- number is a 64-bit float; use integer paise or bigint for money.

## Common follow-up questions

- What is the difference between \`object\`, \`Object\` and \`{}\`?
- Why does \`let x = "a"\` give string but \`const x = "a"\` give "a"?
- When should you annotate a function's return type explicitly?
- What is contextual typing?

## Interview tips

- Say "annotate boundaries, infer the inside"; it is the answer interviewers look for.
- Mention literal widening with const vs let to show depth beyond a type list.
- Avoid listing types for two minutes; pick the interesting ones (void, never, unknown) and explain them.

## Concepts covered

Primitive Types, Type Annotations, Type Inference, Literal Widening, void and undefined

Previous: [Why TypeScript? JS vs TS](https://www.internhack.in/learn/interview/typescript-interview/ts-why-typescript) · Next: [Arrays, Tuples & Enums](https://www.internhack.in/learn/interview/typescript-interview/ts-arrays-tuples-enums) · [All of TypeScript Interview](https://www.internhack.in/learn/interview/typescript-interview)

## More TypeScript Interview questions

- [Functions & Overloads](https://www.internhack.in/learn/interview/typescript-interview/ts-functions-overloads)
- [Object Types & Optional Props](https://www.internhack.in/learn/interview/typescript-interview/ts-object-types)
- [Union & Intersection Types](https://www.internhack.in/learn/interview/typescript-interview/ts-union-intersection)
- [Literal Types & const Assertions](https://www.internhack.in/learn/interview/typescript-interview/ts-literal-const)
- [unknown vs any vs never](https://www.internhack.in/learn/interview/typescript-interview/ts-unknown-any-never)
- [Type Assertions & Non-Null](https://www.internhack.in/learn/interview/typescript-interview/ts-type-assertions)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [TypeScript Interview](https://www.internhack.in/learn/interview/typescript-interview)
