TypeScript Simple Types

TypeScript's simple types - string, number, and boolean - describe the most basic building blocks of your data.

The three core primitive types

TypeScript builds on JavaScript's primitive types by letting you annotate variables, parameters, and return values with them explicitly. The three most common simple types are string, number, and boolean, matching the equivalent JavaScript primitives.

Example

let firstName: string = "Ada";
let age: number = 28;
let isEmployed: boolean = true;

// Reassigning with the wrong type is a compile-time error
// age = "twenty-eight"; // Error: Type 'string' is not assignable to type 'number'.

Type inference

You don't always have to write type annotations. When you initialize a variable, TypeScript automatically infers its type from the assigned value. Explicit annotations are still useful for function parameters, since there is no initial value for the compiler to infer from.

Example

let city = "London";     // inferred as string
let population = 8900000; // inferred as number

// city = 42; // Error: Type 'number' is not assignable to type 'string'.

function describeCity(name: string, pop: number): string {
  return `${name} has a population of ${pop.toLocaleString()}.`;
}

console.log(describeCity(city, population));

Arrays and other simple type variants

Simple types can be combined into arrays using square brackets, and multiple possible types can be expressed with a union using the pipe (|) symbol. These building blocks appear constantly once you move past single values.

  • string - textual data, always wrapped in quotes in code.
  • number - both integers and floating point values; TypeScript does not distinguish int from float.
  • boolean - only the literal values true or false.
  • string[] or Array<string> - an array containing only strings.
  • string | number - a union type, meaning the value can be either a string or a number.

Example

let scores: number[] = [95, 88, 76];
let id: string | number = "abc123";
id = 42; // still valid - id can be either a string or a number

function printScore(score: number): void {
  console.log(`Score: ${score}`);
}

scores.forEach(printScore);
Note: Let TypeScript infer types for local variables with obvious initial values. Reserve explicit annotations for function parameters, return types, and cases where inference would be too broad.
Note: Avoid using the wrapper object types String, Number, and Boolean (capitalized) for annotations - always use the lowercase primitive types string, number, and boolean.
TypeExample valueNotes
string"hello"Any quoted text or template literal
number42, 3.14, -7No separate int/float types
booleantrue / falseOnly these two literal values
string[]["a", "b"]Array of strings
string | number"abc" or 123Union - value can be either type

Exercise: TypeScript Simple Types

Which of these is a valid simple/primitive type in TypeScript?