Type errors: when a number is secretly a string
Totals that concatenate, sorts that put 10 before 9, comparisons that refuse to run.
What is type error?
A value is not the type the code assumes. Python usually raises immediately; JavaScript usually converts silently and gives a wrong answer, which is worse because nothing tells you anything went wrong.
Why it happens
Data crossing a boundary loses its type. Form fields, JSON, query strings and CSV files all arrive as text. JSON object keys are always strings even when they look like numbers. JavaScript's + means addition or concatenation depending on its operands, and its default sort compares elements as strings.
How to recognise it
- A total is a string of digits stuck together rather than a sum.
- Sorting puts 10 before 9 — string ordering, not numeric.
- KeyError on a key you can see in the printed dict (it is "1", not 1).
- In Python 3, / always returns a float, so it can never be an index.
Errors and symptoms this causes
- TypeError: unsupported operand type(s)
- TypeError: '>' not supported between instances of 'str' and 'int'
- TypeError: list indices must be integers or slices, not float
- sort puts 10 before 9
- numbers concatenating instead of adding
How to fix it
Convert once, at the boundary where data enters, rather than scattering int() and Number() through your logic. Use === over == in JavaScript so type mismatches fail loudly. When a value surprises you, print its type before you print its value.
Practise type errors
Working code with one bug in it. Find it, fix it in the browser, and see the explanation. No account needed.