18

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?

1 Answer 1

30

A type guard/predicate function:

function isText(data: unknown): data is string {
  return typeof data === 'string';
};
Sign up to request clarification or add additional context in comments.

8 Comments

it helps, but i try to avoid any, is there a solution without using any? I want to specify that data could be only a string like data:string.In your example i specify that returned value could be a value from ANY
You can use unknown instead. Honestly I don't see anything bad in using any in this particular case
@captain-yossarian, in the case above we don't specify that data could be only string, we said that returned value could be anything. In this way i think i loose the strict checking types.
Return valud of isText is a bollean type while argument of function could be anuthing
No, data is string means that it is a special syntax of a typeguard. isText returns boolean and helps TS to narrow the type. It is a confirmation that if isText returns true - data is string
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.