Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 96 ยท Basic Types

Primitive Types

Learn TypeScript's primitive types - string, number, boolean, bigint, symbol, null and undefined - plus literal values, typeof results and the wrapper-type trap.

JavaScript has seven primitive types: simple, immutable values that aren't objects. TypeScript gives each of them a type with the same name, written in lowercase: string, number, boolean, bigint, symbol, null and undefined. Everything else, from arrays and functions to dates and maps, is an object, and gets its own lessons later in this chapter.

You've already used the first three in Your First Types. This lesson goes deeper: how TypeScript treats each primitive, the rules that trip people up (mixing bigint with number, the uniqueness of symbols, null versus undefined), what the JavaScript typeof operator reports for each one, and why you should never write String with a capital S as a type.

The seven primitives at a glance

Type Example values Notes
string 'hello', "hi", `Total: ${n}` Text of any length, including empty ''
number 42, -0.5, 1e6, NaN, Infinity One type for integers and decimals
boolean true, false Exactly two values
bigint 42n, 2n ** 64n Whole numbers of any size
symbol Symbol('id') Unique identifiers, often used as keys
null null "Intentionally empty"
undefined undefined "Not set", the default for missing values

Primitives are compared by value: two strings with the same characters are equal, even if they were built separately. And they're immutable: string methods like toUpperCase() return a new string instead of changing the old one.

string

A string holds text. Single quotes, double quotes and backticks all produce the same type; backticks additionally allow ${...} interpolation and line breaks. TypeScript knows every string method, so it checks both the method names and their arguments:

TypeScript Working with strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints Grace Hopper 12, gh, ....Grace Hopper, the sentence, and true [ 'Grace', 'Hopper' ]. Interpolating a number inside a template literal is fine; TypeScript knows it will be turned into text. The JavaScript course covers the full toolbox in String Methods.

number

JavaScript has a single numeric type for integers and decimals alike, and so does TypeScript: there's no int, float or double. Every number is a 64-bit floating-point value, which brings two well-known consequences: decimal fractions aren't always exact, and integers are only exact up to Number.MAX_SAFE_INTEGER (9,007,199,254,740,991).

TypeScript Numbers and their special values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output shows 59.97 twice. This multiplication happens to come out clean, but decimal math often doesn't, as the next line proves: 0.30000000000000004 false. That's why money is usually stored as whole cents and formatted with toFixed. After that come 1000000 9007199254740991, then 9007199254740992: the + 1 was lost because the result is beyond the safe range.

Note that NaN and Infinity are numbers as far as TypeScript is concerned. Number('abc') type-checks as number even though the result isn't useful, so validating numeric input still needs a runtime check such as Number.isNaN or Number.isFinite. Underscores like 1_000_000 are numeric separators that make big literals readable; they don't change the value. For more, see Numbers.

Formatting and converting numbers

Numbers have a few methods you will use constantly. They return strings (the parsing functions return numbers), so the result of toFixed is a string, not a number:

TypeScript Number formatting methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is 1234.57, 1234.57, 1.23e+3, then ff 11111111, then 255 5, then false true, and finally string. toFixed(n) keeps n digits after the decimal point, toPrecision(n) keeps n digits in total, and toExponential(n) writes the number as a mantissa and a power of ten. toString(radix) converts to any base from 2 to 36, and parseInt(text, radix) goes the other way. Never compare floating-point results with ===; check that the difference is smaller than a tolerance such as Number.EPSILON. For locale-aware output such as currency, use Intl.NumberFormat in the browser.

boolean

A boolean is true or false. Comparisons, !, and methods like includes or startsWith produce booleans:

TypeScript
const isMember: boolean = true;
const total = 120;
const freeShipping = isMember || total > 100;   // boolean
const isEmpty = 'hello'.length === 0;          // boolean

In conditions, JavaScript also accepts "truthy" and "falsy" values of other types, such as if (name) for a string. TypeScript allows that, and even uses it to narrow types, as you'll see in Narrowing. But a variable declared as boolean only accepts the two real values: let done: boolean = 'yes' is the error Type 'string' is not assignable to type 'boolean'.

bigint

A bigint is a whole number of any size, written with an n suffix (42n) or created with BigInt(...). It's the right tool for very large integers such as IDs from a database, cryptography or exact factorials. BigInt needs a target of ES2020 or later, which every modern configuration uses.

TypeScript Arbitrary-size integers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output starts with 18446744073709551616n, then 9007199254740993n 9007199254740992, showing that the bigint keeps the exact value where the number loses it. 7n / 2n is 3n: bigint division drops the fractional part (toward zero, so -7n / 2n is -3n). The last line prints 10.5 bigint.

The most important rule: you can't mix bigint and number in arithmetic. JavaScript throws a TypeError at runtime if you try, and TypeScript catches it earlier:

TypeScript Mixing bigint and number (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The error is main.ts(4,13): error TS2365: Operator '*' cannot be applied to types 'bigint' and 'number'. Convert one side explicitly: items * BigInt(pricePerItem) gives 30n, and Number(items) * pricePerItem gives 30. Choose Number(...) only when you know the bigint fits in the safe range. Comparisons like 10n > 3 are allowed, because they don't lose precision. BigInt and Symbol covers the JavaScript details.

symbol

A symbol is a value that is guaranteed to be unique. Every call to Symbol() creates a new one, even with the same description. Symbols are mainly used as object keys that can't clash with other keys and don't show up in Object.keys or JSON.stringify:

TypeScript Symbols as unique keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints false, Symbol(userId) userId, then hunter2, [ 'name' ] and {"name":"Ada"}. The symbol-keyed property is there, but invisible to the usual key listings.

Look at the first two lines: a and b are annotated as symbol. Remove the annotations and TypeScript reports TS2367: This comparison appears to be unintentional because the types 'typeof a' and 'typeof b' have no overlap. That's because a const initialized with Symbol() gets a special, narrower type called unique symbol: each such constant has a type of its own that no other symbol shares. TypeScript knows two different unique symbols can never be equal, so it flags the comparison as a mistake. Unique symbols are what make account[SECRET] precisely typed as string.

TypeScript
const KEY: unique symbol = Symbol('key');   // explicit; only allowed on const and static readonly
let other = Symbol('other');                // plain symbol: let can be reassigned

You'll meet built-in symbols like Symbol.iterator and Symbol.dispose in Iterators and Generators and using Declarations.

null and undefined

Both mean "no value", with a difference in intent:

  • undefined is what JavaScript gives you automatically: a variable that was never assigned, a missing property, a parameter nobody passed, or a function with no return.
  • null is something you assign on purpose to say "deliberately empty", like a selected item that hasn't been chosen yet.

In strict mode, they are separate types. A string can never be null or undefined; if a value may be missing, the type has to say so with a union such as string | null:

TypeScript Values that may be missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

It prints null undefined, nothing selected, selected: TEAL, true false and no nickname. Inside label, TypeScript requires the color === null check before calling toUpperCase(), and after the check it knows color is a string. That's strictNullChecks at work. The | syntax is a union type, explained fully in Union Types. The JavaScript side of the story is in null and undefined.

Pick one "empty" value per API and stick to it. Many TypeScript code bases use undefined for "missing" everywhere, because that's what optional properties and parameters produce, and reserve null for values that come from JSON or the DOM, where null is the convention.

Literal values are types too

Every primitive value can also be used as a type of its own, called a literal type. The type 'yes' allows only the string 'yes'; the type 404 allows only the number 404:

TypeScript
let answer: 'yes' = 'yes';
answer = 'no';   // error: Type '"no"' is not assignable to type '"yes"'.

let direction: 'up' | 'down' = 'up';
direction = 'down';   // fine
direction = 'left';   // error

A single literal type is rarely useful, but unions of literals are everywhere: 'light' | 'dark', 200 | 404 | 500, true as "always true". You saw in Type Inference that const variables get literal types automatically. Literal Types and as const covers them in depth.

typeof at runtime

JavaScript's typeof operator returns a string naming a value's runtime type. TypeScript understands it and uses it to narrow types, which makes it the main tool for checking primitives at runtime:

TypeScript What typeof reports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The loop prints string, number, boolean, bigint, symbol, undefined, object, object, object, function, and the last line prints a string of length 5 / a numeric value: 5 / a numeric value: 5. Three results need care:

Value typeof result Why
null 'object' A historical bug in JavaScript that can never be fixed. Check value === null instead.
arrays 'object' Arrays are objects. Use Array.isArray(value).
functions 'function' The only object that gets its own result.

The samples array is typed unknown[], meaning "values of any type that must be checked before use". any, unknown, never and void explains unknown, and in TypeScript code typeof also has a second, compile-time meaning that you'll learn in keyof, typeof and Indexed Access Types.

The wrapper-type trap: string vs String

JavaScript has object wrappers named String, Number, Boolean, BigInt and Symbol. TypeScript has types with those capitalized names too, but they describe the wrapper objects, not the primitives. Using them as types is a mistake:

TypeScript String is not string (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The compiler explains it clearly:

TEXT
main.ts(2,7): error TS2322: Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.

The rule is simple: always use the lowercase names string, number, boolean, bigint and symbol in types. The capitalized names are only useful as functions, as in String(42) or Number('3.5'), which convert values to primitives.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Does const total = 5n + 2; compile?

    bigint and number can't be mixed in arithmetic. Write 5n + 2n, or convert one side with BigInt() or Number().
  2. 2. What does console.log(typeof null) print?

    typeof null is 'object', a long-standing JavaScript quirk. To check for null, compare with value === null.
  3. 3. With strict mode on, which declaration is valid?

    With strictNullChecks, null and undefined must be part of the type. Wrapper types like String also aren't assignable to string.
  4. 4. What is the type of KEY in const KEY = Symbol('key');?

    A const initialized with Symbol() gets the narrower type unique symbol: a type shared by no other symbol.
  5. 5. What does console.log(7n / 2n) print?

    bigint division discards the fractional part, rounding toward zero, so 7n / 2n is 3n.

Summary

  • TypeScript's primitive types are string, number, boolean, bigint, symbol, null and undefined, always written in lowercase.
  • number covers integers and decimals (64-bit floating point); NaN and Infinity are numbers too, and integers are exact only up to Number.MAX_SAFE_INTEGER.
  • bigint (42n) holds exact integers of any size; it can't be mixed with number in arithmetic (TS2365), and its division drops fractions.
  • Every Symbol() is unique; a const symbol gets the type unique symbol.
  • In strict mode, null and undefined are separate types; allow them explicitly with unions like string | null.
  • Every primitive value is also a literal type, such as 'yes' or 404.
  • typeof returns 'string', 'number', 'boolean', 'bigint', 'symbol', 'undefined', 'object' (also for null and arrays) or 'function', and TypeScript narrows types with it.
  • Never use String, Number or Boolean as types; they describe wrapper objects.

Next: Arrays and Tuples โ€” typing lists of values, readonly arrays and fixed-length tuples.