Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 96 · Getting Started

Your First Types

Add type annotations to variables, parameters and return values, and learn to read TypeScript errors - codes, line and column numbers and multi-line messages.

A type annotation is a colon followed by a type, written after the name it describes: let score: number. It tells TypeScript what kind of value is allowed in that place. From then on, the compiler checks every assignment, every call and every property access against that promise.

In this lesson you'll annotate variables, function parameters, return values and simple objects, and you'll learn the most useful skill in TypeScript: reading a type error quickly and knowing what to fix. Everything here builds on the basic types from JavaScript (strings, numbers and booleans), which the next chapter covers in depth in Primitive Types.

Annotating variables

Write the type after the variable name, separated by a colon:

TypeScript Variables with annotations

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 MIRA 50 true. The three most common types are written in lowercase:

Type Values Examples
string Text 'Mira', "hi", `Score: ${score}`
number All numbers, integers and decimals 0, 42, -3.5, NaN
boolean Truth values true, false

A variable keeps its type for its whole life. You can change its value as often as you like with let, but only to another value of the same type. Try adding score = 'lots'; to the editor: the run stops with Type 'string' is not assignable to type 'number'.

You often don't need these annotations. When a variable has an initial value, TypeScript works out the type by itself: let score = 0 is already a number. Annotations are shown on everything in this lesson so you can see the syntax. Type Inference explains when to leave them out, which is most of the time for variables.

Declaring now, assigning later

Annotations matter most when a variable starts without a value. TypeScript then knows what it may hold, and it also tracks whether you've assigned it yet:

TypeScript
let message: string;

if (Math.random() > 0.5) {
  message = 'heads';
} else {
  message = 'tails';
}

console.log(message); // fine: assigned on every path

If one branch forgot to assign message, using it afterwards would fail with TS2454: Variable 'message' is used before being assigned. In JavaScript you'd just get undefined.

Annotating functions

Functions are where annotations pay off the most. Each parameter gets its own type, and the return type comes after the parameter list:

TypeScript Parameters and return types

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 Ada Lovelace, 9 and false true. The annotations do three jobs at once:

  • At the call site, the compiler checks that you pass the right number of arguments, each of the right type.
  • Inside the function, it knows exactly what each parameter is, so first gets all the string methods and a + b is known to be arithmetic, not string joining.
  • At the return, it checks that every return statement produces the promised type, and that a string function doesn't end without returning.

A function that doesn't return anything useful has the return type void:

TypeScript
function logScore(name: string, points: number): void {
  console.log(`${name} scored ${points}`);
}

Arrow functions take annotations in the same places:

TypeScript
const double = (n: number): number => n * 2;
const shout = (text: string): string => text.toUpperCase() + '!';

The whole Functions chapter goes much further: optional and default parameters, rest parameters, callbacks and overloads.

Always annotate parameters. TypeScript can infer most things, but it can't guess what callers will pass. In strict mode, a parameter without a type is an error (TS7006: Parameter 'x' implicitly has an 'any' type.), as you'll see in Strict Mode Explained.

Annotating objects

An object type lists its properties and their types inside braces, separated by semicolons:

TypeScript An object type

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 { title: 'Learning Types', pages: 336, inStock: true } and then the sentence. The object must have exactly the listed properties, with the right types. Missing a property is an error, and so is adding an unknown one in an object literal. Writing the same long type twice gets tiring, so you'll soon learn to give it a name with Type Aliases or Interfaces, and Object Types covers optional and readonly properties.

Reading type errors

Errors are where TypeScript talks to you, so it's worth learning to read them fluently. Here's a program with four separate mistakes:

TypeScript Four mistakes, four errors (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 output is the error list, and nothing runs:

TEXT
main.ts(2,1): error TS2322: Type 'string' is not assignable to type 'number'.
main.ts(4,7): error TS2741: Property 'age' is missing in type '{ name: string; }' but required in type '{ name: string; age: number; }'.
main.ts(10,7): error TS2322: Type 'number' is not assignable to type 'string'.
main.ts(11,24): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

The anatomy of an error

Take the first line apart:

Part Meaning
main.ts The file. In our editor it's always main.ts.
(2,1) Line 2, column 1: where the problem starts. Columns count from 1.
error The severity. TypeScript errors are always errors; there are no warnings.
TS2322 The error code. Every kind of problem has a stable number.
Type 'string' is not assignable to type 'number'. What went wrong, in words.

The message usually follows a pattern: "Type A is not assignable to type B" means "you gave me an A, but this place needs a B". The first type is what you have, the second is what's expected. Read it that way and most errors explain themselves.

The codes you'll see most

You don't need to memorize codes, but a few appear so often that recognizing them saves time. Searching the web for a code like "TS2345" also finds explanations quickly.

Code Typical message Usual cause
TS2322 Type 'X' is not assignable to type 'Y'. Assigning or returning a value of the wrong type
TS2345 Argument of type 'X' is not assignable to parameter of type 'Y'. Passing the wrong type to a function
TS2554 Expected 2 arguments, but got 1. Too few or too many arguments
TS2339 Property 'x' does not exist on type 'Y'. A property the type doesn't have
TS2551 Property 'x' does not exist... Did you mean 'y'? A typo in a property name
TS2741 Property 'x' is missing in type ... but required in type ... An object without a required property
TS7006 Parameter 'x' implicitly has an 'any' type. A parameter without an annotation
TS18048 'x' is possibly 'undefined'. Using a value that might be missing

Best Practices and Common Mistakes walks through each of these with fixes.

Multi-line errors

When types are nested, TypeScript explains the mismatch step by step, indenting each level deeper. This is called an elaboration:

TypeScript An error with an explanation chain (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 spans several lines:

TEXT
main.ts(7,31): error TS2345: Argument of type '(amount: string) => number' is not assignable to parameter of type '(amount: number) => number'.
  Types of parameters 'amount' and 'amount' are incompatible.
    Type 'number' is not assignable to type 'string'.

Read the last line first: it names the actual conflict. Here applyDiscount will call rule with a number, but halfOff wants a string. The lines above tell you where in the bigger types that conflict lives. Change amount: string to amount: number (and drop the Number(...)), and it runs, printing 40.

Strategies for fixing errors

  • Fix the first error first. One mistake can trigger several errors further down. Fixing it often makes the others disappear.
  • Go to the exact column. The column points at the expression TypeScript is unhappy with, which isn't always where the real mistake is. In the label error above, the problem might be the annotation string, not the call.
  • Decide which side is wrong. "Not assignable" means the two sides disagree. Sometimes the value is wrong; sometimes the type you wrote is.
  • Don't silence errors. Casting with as or using any hides the message but keeps the bug. Later lessons show the honest fixes.

The editor experience

This course's editors show errors after you press Run. In a professional editor such as VS Code, the TypeScript language service runs constantly in the background and gives you much more:

  • Red squiggles under errors while you type, with the full message on hover.
  • Hover types: point at any variable to see its type, for example let score: number.
  • IntelliSense: after book., a list shows exactly title, pages and inStock, with their types.
  • Signature help: while typing fullName(, a popup shows fullName(first: string, last: string): string.
  • Quick fixes: a light bulb offers to add a missing property, import a name or fix a typo.
  • Safe renames: renaming pages updates every use across the project, and only real uses, not unrelated text.

You get most of these even in plain .js files, because the same language service powers JavaScript support in VS Code. TypeScript just gives it more information to work with.

Here's one last example to play with. Try breaking it in different ways, then read each error:

TypeScript Break this 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.

It prints 21.5 °C and 70.7 °F. Ideas: pass '21.5' instead of a number, remove city from the object, call formatTemperature with one argument, or misspell celsius as celcius on line 12.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which line is a correct type annotation?

    The type goes after the name, separated by a colon: name: type = value.
  2. 2. What does the error Type 'string' is not assignable to type 'number' tell you?

    The first type is what you gave; the second is what the place expects. Here a string went into a number slot.
  3. 3. In main.ts(11,24): error TS2345: ..., what are 11 and 24?

    The two numbers in parentheses are the line and the column (both counted from 1) of the expression TypeScript is complaining about.
  4. 4. Does this compile? function total(a: number, b: number): number { return a + b; } followed by total(5);

    TypeScript checks the number of arguments as well as their types. A missing argument is reported as TS2554.
  5. 5. A multi-line error has three indented lines under the first one. Where should you usually look first?

    Elaborations go from the big picture to the specific mismatch. The innermost line usually says exactly which types disagree.

Summary

  • A type annotation is : Type after a name: let score: number, function f(x: string): boolean.
  • The everyday types are string, number and boolean, always written in lowercase.
  • Annotate function parameters always and return types when you want the compiler to enforce them; use void for functions that return nothing.
  • Object types list properties: { title: string; pages: number }. Missing or unknown properties are errors.
  • Errors read main.ts(line,column): error TSxxxx: message. "Type A is not assignable to type B" means you gave an A where a B is needed.
  • Read multi-line errors from the innermost line, fix the first error first, and never hide errors with any.
  • Editors use the TypeScript language service for squiggles, hover types, autocompletion and safe renames.

Next: Type Inference — how TypeScript figures out types on its own, and when you should still write them.