
· typescript · 2 min read
TypeScript type narrowing
A quick tour of various dashboards available in Rails 8 to monitor what is going on under your app
What is type narrowing in TypeScript
If you’re not comfortable with “type narrowing”, replace it by “type guessing”.
At runtime, TS is sometimes unable to guess what type your variable is about.
Of course, for let a: string = "foo"
, TS is able to guess (better, it is certain) that a can only be a String.
But what if let a: string | number | null = null
?
Well, when not null, a could be string or number. This cannot be detected at runtime.
function spent(amount: number | string): string {
return `You spent ${amount.toLowerCase}`
}
This won’t work.
TS is unable to “guess” if “amount” is “string” or “number”. Well, toLowerCase will work on string
, but not with number
.
But, a simple “if” solves it :
function spent(amount: number | string): string {
let res = ""
if (typeof amount === "string") {
res = `You spent ${amount.toLowerCase}`
} else if (typeof amount === "number") {
res = `You spent ${amount.toString}`
}
return res
}
You can copy/paste the above in the TypeScript playground : no error are shown.
How great! TS is able to guess type at runtime.
So, again, if you are lost with “type narrowing”, replace by “type guessing at runtime”.
Best,
David.