boolean, number and string
Almost every task in our tracker is made of three kinds of value: a yes-or-no flag, a count or an amount, and some text. TypeScript has one primitive type for each, and you will write them more than any other type.
The rule
Three everyday primitives: boolean, number, string — always lower case.
let done: boolean = false;
let id: number = 7;
let estimateHours: number = 1.5;
let title: string = "Buy milk";boolean— exactly two values,trueandfalse.number— every JavaScript number: whole numbers, decimals, negatives, and the special valuesNaNandInfinity. There is no separateintorfloattype. (Very large whole numbers use a different primitive,bigint, written like10n.)string— text in single quotes, double quotes or backticks. Template strings like`Task ${id}`are strings too.
Why lower case? Boolean, Number and String with capitals also exist, but they name JavaScript's wrapper objects, created with new String("x"). You almost never want those. The lower-case names are the primitive types, and they are what your values actually are.
Remember from inference: when a variable has an initial value, the annotation is optional. let done = false is already a boolean. Annotations on primitives matter most on function parameters:
function rename(id: number, title: string): boolean {
// ...
return true;
}
rename("7", "Buy bread"); // error: "7" is a string, not a numberTypeScript does no conversion. "7" and 7 are different types, even though JavaScript would sometimes blur them together with ==.
The shortcut
For any value, ask "Yes-or-no, amount, or text?" That picks boolean, number or string. Then check the case of the first letter: always lower.
"Mark as urgent" checkbox
A yes-or-no answer, so
urgent: boolean.
A trap worth noticing: values from HTML inputs, URLs and JSON text often arrive as strings, even when they look like numbers. The type must match what the value is, not what it looks like. Convert with Number(...) first, then call it a number.
Drills
Answer fast — trust the rule.
Which type should hold an estimate of 2.5 hours?
Why is string preferred over String?
function setDone(done: boolean) {} is called as setDone("true"). What happens?
What is the type of NaN in TypeScript?
Remember
- Three everyday primitives: boolean, number, string — always lower case.
- Ask yes-or-no, amount, or text to pick the type.
- Trap: input from forms, URLs and JSON is often a string until you convert it.
