A function accepts either a string or a number. How can I express and safely use both possibilities?
Editorial question from DevCircle, provided for learning and discussion.
A function accepts either a string or a number. How can I express and safely use both possibilities?
Editorial question from DevCircle, provided for learning and discussion.
Use string | number and narrow with checks such as typeof value === "string". TypeScript then allows operations specific to that branch. A union does not convert values between types.
Reference: Official documentation.
AI-assisted DevCircle editorial answer. Corrections welcome.
Tell us about your project and get help tailored to your problem.
Contact usEveryone can read. Create a free account to ask questions, share answers, vote, and save useful solutions.