01 / 05
Adding types
INPUT · Slides
Your first TypeScript
02 / 05
Why bother writing types?
JavaScript never complains about what you put in a variable. Drop a string into one you meant for numbers and it carries on quite happily.
The trouble comes afterwards. Your sums go strange, and only then do you notice. And the cause is often a long way further up the file.
TypeScript tells you before anything runs.
03 / 05
The type goes after :
Put a : after the name of the variable, then the name of the type. For text that is string.
The = "Yui" part is just as before. The type declaration slots in between.
const personName: string = "Yui";console.log(personName);Result
Yui
04 / 05
A mismatch stops you
Try to put a number into a variable you declared as string, and it is an error before it ever runs.
The screen says "Type 'number' is not assignable to type 'string'". That is a note TypeScript shows only to you, the person writing it, so you can fix it before running.
const personName: string = 123;Result
Type error: Type 'number' is not assignable to type 'string'.
05 / 05
When it runs, you get exactly what JavaScript gave you
Types are there for the check before you run. Right before your code runs, every type is stripped out and what is left is plain JavaScript.
So console.log prints the same, and your sums come out the same, as they did in JavaScript. Writing a type never changes what you see.
const price: number = 150;console.log(price * 2);Result
300