WeCodeAcademy

Narrowing

With a union you cannot use methods that only one member has, until you narrow the type with a check such as typeof.

Exampletypescript
Open in editor »

Inside each branch, TypeScript knows which type you have. Without the check:

Exampletypescript
Open in editor »
Quick check

Why does `value.toUpperCase()` fail on `string | number`?

Your turn: write the code

Write twice(v: string | number): string | number. For a number return v * 2; for a string return it repeated twice (v + v). Print twice(4) and twice("ab").

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.