When TypeScript catches JavaScript’s little lies

I love JavaScript’s quirks. They can be frustrating, but I still get a kick out of noticing them. TypeScript is great at calling these out.

Recently, I tried something simple: window.location = "some string"

type 'string' is not assignable to type 'Location'

Type 'string' is not assignable to type 'Location'.

Wat.

I almost slapped on a @ts-ignore, but paused to understand why code I’d written countless times was failing.

The answer? JavaScript treats window.location like a string, but TypeScript knows it’s an object, so that assignment fails. The fix is to use window.location.href, which is a string. MDN even notes that browsers treat assigning a string to window.location as a synonym for setting window.location.href.

JavaScript lets you get away with a lot. TypeScript isn’t so forgiving and I kind of like that.


me
John-George Sample is a software engineer based in Pittsburgh, PA. He uses vim, btw.