Emmanuel Akinfulubi

TypeScriptBasic

Fix a type error when assigning a value in TypeScript

4 Watch the type checker refuse an assignment

easy

Declare a variable as a number, then try to put text in it. Show what the compiler says, and show the two honest ways to end up with text instead.

Stuck? Three hints, smallest first
  1. 1. The error is TS2322, "Type ‘string’ is not assignable to type ‘number’".
  2. 2. You cannot fix it by assigning. You either convert the value or use a different variable.
  3. 3. String(n) converts a number to text. It always succeeds.

The answer, and proof it works

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)}`)
  );
}

let seats: number = 14;

// This is the error the exercise is about. Uncomment it and the build stops:
// seats = 'fourteen';
//         ^ Type 'string' is not assignable to type 'number'. (TS2322)

// Fix one: convert, and keep the two values in separate variables.
const seatsAsText: string = String(seats);

// Fix two: if it really can be either, say so in the type.
let flexible: number | string = 14;
flexible = 'fourteen';

console.log(seats, typeof seats);
console.log(seatsAsText, typeof seatsAsText);
console.log(flexible, typeof flexible);

test('the number is untouched', seats, 14);
test('converted to text', seatsAsText, '14');
test('a union accepts both', typeof flexible, 'string');

Output


      

This is the whole point of TypeScript in one error. Nothing about the running program changed; the checker simply refused a line that would have produced "fourteen" * 2 === NaN later. When you genuinely need two shapes, write the union number | string rather than reaching for any.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.