Declare typed variables in TypeScript
1 A name and an age, with types
easyDeclare one variable holding a person's name as text and another holding their age as a number. Print both. Annotate each one so the reader can see the type without running anything.
Stuck? Three hints, smallest first
- 1. A type annotation goes after the variable name and a colon:
let x: number. - 2. The two type names you want are
stringandnumber, both lowercase. - 3. You do not have to annotate these at all. Do it here anyway, then note in a comment that TypeScript already knew.
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 personName: string = 'Amaka Obi';
const age: number = 31;
console.log(personName, age);
// The annotations above earn nothing: TypeScript reads 'Amaka Obi' and already
// knows it is a string. Lesson: annotate when it adds information, not by habit.
const inferred = 'Chidi'; // inferred as string, no annotation needed
test('name', personName, 'Amaka Obi');
test('age', age, 31);
test('inference still gives a string', typeof inferred, 'string');
Output
Notice the annotations are optional here. const personName: string = 'Amaka Obi' tells you nothing the value did not already say. Save annotations for function parameters and for empty containers, where there is nothing to read the type from.