Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

355
Views
How to use a variable as string or object in TypeScript?

I have a variable that can either be a string or object like this:

value?: string | { name: string, type: string }

Trying something below but I get a compile error:

console.log(value?.name || value)
console.log(value?.type)

How can use this variable if it can be either type?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In this case you can do:

console.log(typeof value === 'string' ? value : value?.name)

Typescript can narrow the type using type-guards, see here for more details.

about 4 years ago · Juan Pablo Isaza Report

0

So you have two options

console.log(typeof value === 'string' ? value : value.name);

But as you used ?: in definition for this value (allowing undefined) and as i think that console is only for simple example there

if (value === undefined) {
} else if (typeof value === 'string') {
} else {
}

Would be best.

This issue you found is mostly done because both values for value variable are objects and ts saw that the types are not compatible and asks you to narrow them by hand

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!