V
V
Vann Damm2021-02-19 19:38:06
typescript
Vann Damm, 2021-02-19 19:38:06

How to check the type of function parameters?

Type for object methods - AuthFormsType

type AuthFormsType = {
  [s:string] : (props:FormPropsType | {path:string})=>React.ReactNode;
}


The type used to describe object method props - FormPropsType

export type FormPropsType = {
  formName:string;
  onSubmit:ReturnType<typeof submitHandlersCreator>;
  changeFormStateHandler:ReturnType<changeFormStateHandlerType>;
}


The object itself

const authForms:AuthFormsType = {
  login:(props) =>{
    if(props === typeof FormPropsType ){
      return <Login 
      formName={props.fromName} 
      onSubmit={props.onSubmit} 
      changeFormStateHandler={props.changeFormStateHandler}
      />
    } 
    return <Login path={props.path} />
  },

I need to check what type props have and depending on what type to give this or that component?
What are the possible options for checking prop types?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-02-19
@effect_tw

There are no types in runtime, so you need to check according to what is, for example, write something like this typeguard:

const isFormPropsType = (v: FormPropsType | {path: string}): v is FormPropsType => typeof (v as FormPropsType).formName === 'string';

And accordingly use it to check:
const authForms:AuthFormsType = {
  login:(props) =>{
    if(isFormPropsType(props)){
      return <Login 
      formName={props.fromName} 
      onSubmit={props.onSubmit} 
      changeFormStateHandler={props.changeFormStateHandler}
      />
    } 
    return <Login path={props.path} />
  },

Although I suspect that it is much easier to do in this case:
const authForms:AuthFormsType = {
  login:(props) => {
    return <Login {...props} />
  },

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question