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.
Show me your love ❤️
Top comments (0)