Basics
This tutorial assumes you have a basic understanding of JavaScript. If you are just getting started, it is a good idea to read the JavaScript tutorial first.
Every valid JavaScript file is a valid TypeScript file.
TypeScript adds some really useful features to JavaScript, but the JavaScript interpreter running in your web browser or in Node.js can't understand them. To run a TypeScript program, a build system converts it into JavaScript.
On this website, the TypeScript compiler runs directly in your web browser to produce JavaScript. The generated JavaScript code is then executed in your browser to produce the output shown below.
The TypeScript compiler converted the program above into the standard JavaScript program below.
function greet(name) { console.log(`Hello, ${name}!`);}const age = greet('Alice Smith');
Normally, you would write TypeScript code with a modern editor like VSCode.
Variables
There are three ways to define a variable in TypeScript.
Questions
Strings
A JavaScript string
represents a sequence of characters, like "Hello"
or "42"
.
This is another test
Numbers
JavaScript does not have a special runtime value for integers, so there is no equivalent to int
or float
in languages
like Java and C++.
Everything is simply number
.
Infinity
and NaN
JavaScript has special values to represent infinity (Infinity
) and "not a number" (NaN
).
A common situation where NaN
arises in TypeScript programs is during the conversion of a string
value to number
.
Booleans
A boolean value is either true
or false
.
Arrays
An array is a sequence of values. To specify the type of an array like [1, 2, 3]
, you can either use number[]
or Array<number>
.
Tuples
A tuple is an exact sequence of values.
Notice that you will get a tuple error if the specified sequence is not matched exactly.