Basic types: number, string, boolean in TypeScript
3 The four everyday types
easyDeclare one variable of each type: number, string, boolean and undefined. Do something small with each one and print the result.
Stuck? Three hints, smallest first
- 1.
typeofreturns a string, and for an undefined value that string is"undefined". - 2. Template literals with backticks are the tidiest way to join text and numbers.
- 3. A variable annotated
undefinedcan only ever holdundefined, which is rarely useful on its own.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
const count: number = 7;
const label: string = 'seats';
const isFull: boolean = false;
const notSetYet: undefined = undefined;
const doubled = count * 2;
const shouted = label.toUpperCase();
const flipped = !isFull;
console.log(`${count} ${label} -> doubled ${doubled}`);
console.log('shouted:', shouted);
console.log('flipped:', flipped);
console.log('typeof notSetYet:', typeof notSetYet);
test('arithmetic on a number', doubled, 14);
test('a method on a string', shouted, 'SEATS');
test('negating a boolean', flipped, true);
test('typeof undefined', typeof notSetYet, 'undefined');
Output
These four plus null, bigint and symbol are the whole primitive set. Everything else, arrays and objects and functions included, is an object. Note that typeof hands you a string, which is why it works so well in the narrowing checks you will meet later.