Getting Started
Checking a file with tsc, reading its errors, and types that vanish.
Checking a file
A .ts file is a .js file with types added. The only new thing here is : string:
function greet(person: string) {
return `hi ${person}`
}
console.log(greet("ada"))Your first error
Pass the wrong kind of value and the silence breaks:
function greet(person: string) {
return `hi ${person}`
}
console.log(greet(42))Annotating
A colon and a type, after the name. That is the whole syntax:
function area(width: number, height: number) {
return width * height
}
console.log(area(3, 4))Those two annotations are the only reason the next version is caught:
function area(width: number, height: number) {
return width * height
}
console.log(area(3, "4"))Inference does most of it
Nothing here is annotated, and it still checks clean:
const city = "London"
let count = 0
console.log(city, count)The types are there all the same. Assign the wrong kind of value and you see them:
let count = 0
count = "zero"Running the code
Once it checks clean, node runs the file directly — no build step, no loader:
function greet(person: string) {
return `hi ${person}`
}
console.log(greet("ada"))But node deletes the annotations without checking them, so it runs a broken file just as
happily — same two commands, and the error changes nothing:
function greet(person: string) {
return `hi ${person}`
}
console.log(greet(42))Compiling
For a browser or a published package you need real JavaScript files. Drop --noEmit and
tsc writes them:
export function add(a: number, b: number) {
return a + b
}npx tsc --outDir dist src/main.ts
cat dist/main.jsTypes vanish
An interface describes a shape. It exists for the checker and nowhere else:
interface User {
name: string
}
const u: User = { name: "ada" }
console.log(u.name)Here is what actually runs. The interface is simply gone:
const u = { name: "ada" }
console.log(u.name)Reading an error
Three more worth recognising. A missing property:
interface User {
name: string
age: number
}
const u: User = { name: "ada" }A method that does not exist on the type:
const nums = [1, 2, 3]
console.log(nums.toUpperCase())And a property you never declared:
interface User {
name: string
}
const u: User = { name: "ada", age: 36 }