TypeScript Tutorial
TypeScript Data Types
number, string, boolean, and more store different kinds of values. Pick the type that matches the data.
The type is a contract
Every variable has a type. The type says what kind of value fits and how operators treat it. Choosenumber for counts and measurements, string for text, and boolean for yes or no. TypeScript does not split integers and floating-point the way C++ splits int anddouble. Both live in number.
Example
const seats: number = 24;
const lengthM: number = 1.75;
const open: boolean = true;
const title: string = "StudyGrid";
console.log(seats);
console.log(lengthM);
console.log(open);
console.log(title);boolean prints as true or false. That is normal forconsole.log.
Compile this at /typescript/try with Try it in TypeScript. That editor is only for TypeScript. Python lives at /try. C++ lives at /cpp/try.
A table of common types
| Type | Holds | Example |
|---|---|---|
number | Integers and decimals | 42, 3.14 |
string | Text of any length | "hello" |
boolean | true or false | true, false |
number[] | A list of numbers | [91, 84, 76] |
[string, number] | A pair with fixed slots | ["Mia", 95] |
number[] is the same idea as Array<number>. This tutorial writes the short form. A tuple such as [string, number] has a fixed length and a type per slot.
Arrays and tuples
An array is a list of one type. Index from 0. A tuple is a short, fixed list where each position has its own type: a name and a score, a label and a count.
Example
const scores: number[] = [91, 84, 76];
const player: [string, number] = ["Mia", 95];
console.log(scores[0]);
console.log(scores.length);
console.log(player[0] + " scored " + player[1]);Change 91 and compile again. scores[0] follows that first slot. Putting a string intoscores is a type error.
Division is floating-point
C++ 7 / 2 is 3 when both sides are int. TypeScript7 / 2 is 3.5 because number is floating-point. UseMath.floor when you want to drop the fraction.
Example
console.log(7 / 2);
console.log(Math.floor(7 / 2));any versus unknown
any turns the checker off for that name. You can call anything on it; tsc will not stop you.unknown also accepts any value, but you must narrow it before you use it. Preferunknown when the type is not known yet. Prefer a real type when it is.
Example
const mystery: unknown = "StudyGrid";
if (typeof mystery === "string") {
console.log(mystery.length);
}
const loose: any = "StudyGrid";
console.log(loose.length);The typeof check lets tsc treat mystery as a string inside the block.loose needs no check, which is why any is easy to misuse.
Other types exist
TypeScript also has null, undefined, unions, objects, and generics. This track stays with number, string, boolean, arrays, and tuples until you have a reason to switch. Next: operators, which combine these values.