Type conversion and type assertions in TypeScript
6 Converting between types, and asserting
fairTurn text into a number and back. Use a real conversion function for one direction, and a type assertion for a value the compiler cannot see into. Show why the two are not the same thing.
Stuck? Three hints, smallest first
- 1.
parseInt(text, 10)andNumber(text)both convert. Always pass the radix toparseInt. - 2. A conversion changes the value at runtime. An assertion changes nothing at runtime; it only silences the checker.
- 3.
Number('abc')givesNaN, andNaNis of typenumber, so the checker will not catch it. Guard withNumber.isNaN.
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)}`)
);
}
// Conversion: really happens, at runtime.
const fromText: number = parseInt('42', 10);
const alsoFromText: number = Number('42');
const backToText: string = String(42);
// Conversion can fail, and the failure is still typed number.
const broken = Number('abc');
const safe = Number.isNaN(broken) ? 0 : broken;
// Assertion: a promise to the compiler, with no runtime effect at all.
const loose: unknown = 'actually a string';
const asserted = loose as string;
console.log(fromText, alsoFromText, backToText);
console.log('Number("abc") is', broken, '-> guarded to', safe);
console.log('asserted length:', asserted.length);
test('parseInt converted', fromText, 42);
test('Number converted', alsoFromText, 42);
test('String converted back', backToText, '42');
test('NaN is still a number', typeof broken, 'number');
test('guard replaced NaN', safe, 0);
test('assertion let us use a string method', asserted.length, 17);
Output
Conversion runs; assertion does not. Number(x) produces a new value. x as string produces nothing at all: it is erased, and if you were wrong the program breaks later with no warning. Reach for assertions only when you genuinely know something the compiler cannot, such as a value you just parsed from JSON.