Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring props in the function parameters using TypeScript

Tags:

I'm trying to my component library to use TypeScript and am attempting to convert a stateless functional component in React from ES6/JavaScript to TypeScript. I am wondering how I can avoid duplicating myself while still being able to deconstruct props outside the function while passing it parameters.

My component currently looks like this:

const allowedColors = {   warning: "fa fa-exclamation",   info: "fa fa-info",   success: "fa fa-check",   danger: "fa fa-minus-circle" };  const AlertIcon = ({ className, color, ...props }) => (   <FontAwesomeIcon     {...props}     iconClassName={allowedColors[color]}     className={classNames(`alert-icon-${color}`, className)}     aria-hidden="true"     data-ut="alert-icon"   /> );  AlertIcon.propTypes = {   className: PropTypes.string,   color: PropTypes.oneOf(Object.keys(allowedColors)).isRequired }; 

How would I go about refactoring this into TypeScript?

like image 594
halsdunes Avatar asked Oct 01 '18 23:10

halsdunes


People also ask

What is parameter Destructuring in TypeScript?

When destructuring object parameters in a function, separate the destructured parameters and the type for the specific properties with a colon, e.g. function getPerson({ name, age }: { name: string; age: number }) {} .

Can you Destructure props in a class component?

You can destructure the React props object within the render method inside a React class component. You can also destructure the React props object within a React functional component.

How do you pass a function as props in React functional component TypeScript?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.


1 Answers

type Color = "warning" | 'info'| 'success' | 'danger'  interface IProps {   color: Color }  const AlertIcon = ({ className, color, ...props }: IProps) => { ... } 

now when you use AlertIcon the color prop must be of type Color

to account for passing HTML attributes, like className you can do this:

interface IProps extends HTMLAttributes<HTMLElement> { ... } 

where HTMLElement is your type of element.

like image 142
Uzi Avatar answered Oct 07 '22 18:10

Uzi