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

231
Views
Typescript check if a value is string

I have a component:

export type IDAta = string | number | null;

interface IDAta {
  data?: string | number | null;
  verify: boolean;
}

const App: React.FC<IDAta> = ({
  data = '',
  verify = true,
}) => {

  if ((data || data === 0) {
    return (
      <div>
        {verify && isText(data) ? (
          <Child text={data} />
        ) : (
          data
        )}
      </div>
    );
  }

};

export default App;

isText and Child component expect the parameters only to be string, but doing this verify && isText(data) then i get error in typescript like Type 'number' is not assignable to type 'string'. . This could be solved as follow:

{
  verify && typeof data === 'string' && isText(data) ? ( 
  <Child text = {data as string}/>
  ) : (
    data
  )
}

I am not sure if this solution is ok, because typeof data === 'string' double the logic from isText function which looks like this:

const isText = (data: string) => {
  return typeof data === 'string';
};

Question: What will be the best solution to solve the issue described above?

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

0

A type guard/predicate function:

function isText(data: any): data is string {
  return typeof data === 'string';
};
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!