How do you type and guard a string-or-string-array argument?
Tests union typing and runtime narrowing. Annotate as `string | string[]`, then branch with `Array.isArray()`. Strong answers note `typeof` returns `"object"` for arrays and that assertions bypass safety.
WHAT THIS TESTS: This question evaluates whether you can model a value that may arrive in two shapes using a union type, and whether you know how to safely narrow that union inside a function body. The interviewer cares about your grasp of TypeScript's control-flow analysis and your ability to distinguish compile-time types from runtime JavaScript behavior.
A GOOD ANSWER COVERS: First, type the parameter as a union of string and string array. Second, use a type guard to narrow the union before operating on the value. The idiomatic choice is Array.isArray(arg) because it is a purpose-built runtime check that TypeScript recognizes as a type guard. If the check returns true, TypeScript narrows arg to string array inside that block; otherwise it narrows to string in the else block. Third, explain why typeof on an array returns object, so you cannot use typeof to detect arrays. Fourth, mention that you should avoid type assertions because they override the compiler and remove safety. A concise implementation declares the function with parameter input as string or string array, then writes if (Array.isArray(input)) { input.forEach(...) } else { ... }.
COMMON WRONG ANSWERS: Using typeof arg === "array" is a runtime bug because typeof never returns array; it returns object for arrays. Another red flag is reaching for as string array or as string to force the type instead of narrowing it properly. Some candidates suggest function overloads immediately; while overloads are valid, they are overkill for a simple parameter union and the interviewer may worry you default to complexity. Using instanceof Array is not strictly wrong, but Array.isArray is preferred because it works across realms and is the standard TypeScript-recognized guard.
LIKELY FOLLOW-UPS: The interviewer might ask what happens if null or undefined can also be passed, which forces you to add null to the union and handle it first. They might ask how to make the return type depend on the input, which leads to generics or function overloads. They could also ask why Array.isArray is preferable to instanceof Array, which tests your knowledge of cross-realm objects and prototype chains.
ONE CONCRETE EXAMPLE: A function process takes input typed as string or string array. Inside, if Array.isArray(input) is true, it logs input.join(", "). Otherwise it logs input.toUpperCase().
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.