TypeScript Basics: Syntax Errors vs. Type Errors
Welcome to the Syntax Errors vs. Type Errors lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
In JavaScript, any code with valid syntax will run. In TypeScript, code must have valid syntax and must type check. Only then will it run.
JavaScript: syntax check -> execution.
TypeScript: syntax check -> type check -> execution.What's the difference between a syntax error and a type error? We can think of it by analogy to English. "Vase triangle avocado cat grape" is not valid English syntax. Each of those words is part of English, but they can't be in that order. No English sentence can be made of five nouns in a row.
Likewise,
function return class if varis invalid TypeScript syntax. Each of those words is part of TypeScript, but they can't be in that order. If we try to compile that "code", the compiler rejects its syntax. The type checker never even runs.When our syntax is correct, the compiler checks semantics (types). "That tree is angry" is valid English syntax, but doesn't "type check". Trees can't be angry (outside of fantasy novels).
In TypeScript,
a + bis valid syntax. But if a is a number and b is a boolean, thena + bwon't type check.In this course, you should write "syntax error" when some code has a syntax error. Continue to write "type error" when the syntax is correct, but the types are wrong.
>
function return class if varResult:
syntax error: on line 1: Identifier expected. 'return' is a reserved word that cannot be used here.
>
let a = 1;let b = 2;a + b;Result:
3
>
let a = 1;let b = true;a + b;Result:
type error: Operator '+' cannot be applied to types 'number' and 'boolean'.
>
1 &+ 2Result:
syntax error: on line 1: Expression expected.