-
Notifications
You must be signed in to change notification settings - Fork 0
Typing variables
When writing JavaScript code, it's normal to simply declare a variable by giving it a name and it's initial value, like for example:
let name = 'Someone';Because TypeScript is a superset over Javascript, any JavaScript code that we add inside a .ts will be "valid TypeScript" code as well.
When a variable is declared as above, TypeScript is able to infer which is the type of the declared variable. This means that TypeScript is alreayd doing it's work by setting a type specific value to a variable declared and if we try to assing something else to that variable that will show a TypeScript error.
// shows the TypeScript error - Type 'number' is not assignable to type 'string'
name = 5;But even though TypeScript can automatically infer the type assigned to a variable, it's part of good practices to manually declare the type, by adding a colon after the variable name and a lower case version of the desired type, which would leads us to:
let name: string = 'SomeName';Some other basic types that can be used are number and boolean
let name: string = 'SomeName';
let age: number = 10;
let isAdult: boolean = false;Those notes were written while watching the tutorial videos while taking the classes from the online course Learn TypeScript on Scrimba.
Because english is not my mother language, they can contain some typos and everything written here is based on my understanding about the discussed topics and may not be 100% accurate.
If you want the full course, support the instructor by buying their course on Scrimba.
- Home
- Introduction
- Introduction to TypeScript
- The Pizza Application
- Move to TypeScript
- Defensive Coding
- Typing variables
- Typing Pizza App: part 1
- Custom types
- Typing Pizza App: part 2
- Nested Object types
- Optional Properties
- Typing Pizza App: part 3
- Array Types
- Typing Pizza App: part 4
- Literal Types
- Unions
- Typing Pizza App: part 5
- Typing Pizza App: part 6
- Typing Pizza App: part 7
- Returning Types
- Typing Pizza App: part 8
- Any Type
- Typing Pizza App: part 9
- Utility Types
- Typing Pizza App: part 10
- Generics
- Typing Pizza App: part 11