DEV Community

Cover image for How to use infer in typescript?
Vishesh Tiwari
Vishesh Tiwari

Posted on • Edited on

How to use infer in typescript?

Hi Devs,

Welcome to this exciting article where we’ll explore how to use infer in TypeScript to write cleaner code and avoid duplication. By the end of this read, you’ll be able to effortlessly extract function return types, argument types, and React component props. Let’s dive in!

What You’ll Learn:

  • Inferring Function Arguments: Simplify your code by extracting argument types.

Let's assume on function as example -

const myFunction = (arg0:number,arg1:string,arg2:Object):boolean =>{
  // Business logic
  return true
}
Enter fullscreen mode Exit fullscreen mode

For inferring arguments of myFunction we can use below statement -

type MyArgumentTypes<T> = T extends (...args: infer A) => any ? A : never;
Enter fullscreen mode Exit fullscreen mode
type ArgumentTypes = MyArgumentTypes<typeof myFunction>;
// Initial type:
[arg0: number, arg1: string, arg2: Object]
Enter fullscreen mode Exit fullscreen mode
  • Inferring Function Return Types: Avoid redundancy by inferring return types.

Same like we can extract function return type also using below statement -

type ReturnTypeOfFunction<T> = T extends (...args: any[]) => infer R ? R: never;
Enter fullscreen mode Exit fullscreen mode

Let's start the action -

type ReturnType = ReturnTypeOfFunction<typeof myFunction>;
// Initial type:boolean
Enter fullscreen mode Exit fullscreen mode
  • Inferring React Component Props: Make your React components more manageable by extracting props.

For extracting react component props/type approach will be ,just need to slight changes.

Suppose you have test react component CustomAlert like -

interface Props {
  type: any;
  subTitle: string;
  setShowAlert: Function;
  dataTestId?: string;
}

const CustomAlert: React.FC<Props> = ({ type, subTitle, setShowAlert, dataTestId }) => { }

Enter fullscreen mode Exit fullscreen mode

So for props extraction we can use below statement

type ExtractProps<TComponentOrTProps> = TComponentOrTProps extends React.ComponentType<infer TProps>
  ? TProps
  : TComponentOrTProps;`

type CustomAlertProps = ExtractProps<typeof CustomAlert>
// Initial type: Props
Enter fullscreen mode Exit fullscreen mode

I hope this article will help you to debug/extract props about library function or build function.


Show me your love ❤️

Buy Me A Coffee

Top comments (0)