Basic types
| String | |
| Number | |
| Boolean | |
| Let TS infer |
String
A string holds text between double quotes. The annotation after the colon promises the compiler that only text will ever live in that constant:
const name: string = "Ada";
console.log(name.toUpperCase());
ADA
Because name is known to be a string, the editor can suggest string methods such as toUpperCase. Storing a number in name later would stop the compile with a clear error.
Number
One number type covers integers and decimals alike. There is no separate int or float, which keeps arithmetic annotations short:
const age: number = 36;
const next: number = age + 1;
console.log(next);
37
Both constants promise numbers, so adding them is checked while string concatenation by accident is rejected. Math stays math and text stays text.
Boolean
A boolean holds exactly two values: true or false. Conditions read them directly, with no comparison tricks needed:
const ready: boolean = true;
if (ready) {
console.log("go");
}
go
The if branch runs because ready is true. Assigning a string such as yes to a boolean would fail the compile, which keeps flags honest across the codebase.
Let TS infer
Annotations can be omitted when the starting value already says it all. TypeScript infers string for the constant below, so adding the annotation would only repeat the obvious:
let city = "Paris";
console.log(city.length);
5
Inference is not looseness: city is still a string, and storing a number in it later still fails. Write explicit annotations at function borders and let inference handle the plain cases inside.
Next: any, unknown, never
Article author: Arthur Isaev