The language of the web
JavaScript is the only language that runs natively in browsers. TypeScript adds types for fewer errors.
JavaScript vs TypeScript
| Aspect | JavaScript | TypeScript |
|---|---|---|
| Types | Dynamic | Static |
| Errors | At runtime | During development |
| Files | .js | .ts |
| Compilation | Not needed | Needs tsc |
๐ก Recommendation: Use TypeScript for serious projects.
Fundamental concepts
Variables
const name = "Ana" // Doesn't change
let age = 25 // Can change
// var is obsolete, don't use it
Functions
// Arrow function (preferred)
const add = (a: number, b: number): number => a + b
// Traditional function
function multiply(a: number, b: number): number {
return a * b
}
Arrays
const fruits = ['apple', 'pear', 'grape']
fruits.map(f => f.toUpperCase()) // Transform
fruits.filter(f => f.length > 4) // Filter
fruits.find(f => f === 'pear') // Find one
Objects
interface User {
name: string
age: number
email?: string // Optional
}
const user: User = {
name: "Ana",
age: 25
}
Async/Await
// Call API
async function getUser(id: string) {
const res = await fetch(`/api/users/${id}`)
const data = await res.json()
return data
}
// Use
const user = await getUser('123')
Practice
Useful links
- ๐ TypeScript Handbook
- ๐ JavaScript.info