How to use infer in typescript?

Vishesh TiwariVishesh Tiwari
2 min read

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
}

For inferring arguments of myFunction we can use below statement -

type MyArgumentTypes<T> = T extends (...args: infer A) => any ? A : never;
type ArgumentTypes = MyArgumentTypes<typeof myFunction>;
// Initial type:
[arg0: number, arg1: string, arg2: Object]
  • 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;

Let's start the action -

type ReturnType = ReturnTypeOfFunction<typeof myFunction>;
// Initial type:boolean
  • 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 }) => { }

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

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


0
Subscribe to my newsletter

Read articles from Vishesh Tiwari directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vishesh Tiwari
Vishesh Tiwari

Vishesh Tiwari is a dedicated IT professional with over 5 years of experience. Specializing in the Java Spring Boot and React JS tech stack, Vishesh excels as a Full Stack Java Developer. His skills cover both front-end and back-end development, enabling him to create robust and scalable applications. Additionally, Vishesh has gained valuable experience working with AWS for a year, enhancing his ability to leverage cloud services. Passionate about coding and continuous learning, he stays updated with the latest industry trends and best practices. Connect with Vishesh to explore insights on full stack development and innovative technology.