Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
Asking Avatar asked Dec 07 '25 05:12

Asking


1 Answers

A type guard/predicate function:

function isText(data: unknown): data is string {
  return typeof data === 'string';
};
like image 181
AKX Avatar answered Dec 08 '25 20:12

AKX