๐ŸŒ
React
react.dev โ€บ learn โ€บ typescript
Using TypeScript โ€“ React
To get type-checking, you can use the TypeScript Playground or use a more fully-featured online sandbox. This inline syntax is the simplest way to provide types for a component, though once you start to have a few fields to describe it can become unwieldy. Instead, you can use an interface or type to describe the componentโ€™s props...
๐ŸŒ
React TypeScript Cheatsheets
react-typescript-cheatsheet.netlify.app โ€บ typing component props
Typing Component Props | React TypeScript Cheatsheets
A list of TypeScript types you will likely use in a React+TypeScript app: type AppProps = { message: string; count: number; disabled: boolean; /** array of a type! */ names: string[]; /** string literals to specify exact string values, with a union type to join them together */ status: "waiting" | "success"; /** an object with known properties (but could have more at runtime) */ obj: { id: string; title: string; }; /** array of objects!
๐ŸŒ
React
legacy.reactjs.org โ€บ docs โ€บ typechecking-with-proptypes.html
Typechecking With PropTypes โ€“ React
PropTypes arenโ€™t commonly used in modern React. Use TypeScript for static type checking.
๐ŸŒ
Pluralsight
pluralsight.com โ€บ tech insights & how-to guides โ€บ tech guides & tutorials
Defining Props in React Function Component with Typescript | Pluralsight
We cover several different methods, including destructuring and React.FC. ... This guide will help you properly define the props entering your function components. You'll also learn when defining props as a class or interface type is best and how to provide default values to optional props. TypeScript extends JavaScript features in powerful ways, including the ability to define the structure of an object.
๐ŸŒ
DEV Community
dev.to โ€บ mconner89 โ€บ passing-props-in-react-using-typescript-20lm
Passing props in React using Typescript - DEV Community
November 4, 2020 - Lets assume you're trying to pass a series of props down to a lower component in react, you're not going to do any kind of destructuring, and you're not passing any objects. So calling the lower-level component might look something like this: ... To make TypeScript happy, we need to tell it what to expect on that props object.
๐ŸŒ
Total TypeScript
totaltypescript.com โ€บ react-props-typescript
Strongly Typing React Props with TypeScript | Total TypeScript
September 5, 2023 - This advice comes from TypeScript's performance wiki, as well as a PR from Sentry's codebase that sped up their type checking by removing these intersections in favor of interfaces. So in situations where you're extending from other types, use interfaces. # In general, you should use interface to declare your props.
๐ŸŒ
Steve Kinney
stevekinney.com โ€บ courses โ€บ react with typescript โ€บ complete guide to react component props with typescript
Complete Guide to React Component Props with TypeScript | React with TypeScript | Steve Kinney
1 month ago - These helper types shine when combined to create expressive, reusable prop patterns: // A card component that needs children and refs interface CardBaseProps { title: string; footer?: ReactNode; } type CardProps = PropsWithChildren<CardBaseProps> & RefAttributes<HTMLDivElement>; const Card = forwardRef<HTMLDivElement, CardProps>( ({ title, footer, children }, ref) => { return ( <div ref={ref} className="card"> <header>{title}</header> <main>{children}</main> {footer && <footer>{footer}</footer>} </div> ); } ); // A form field that explicitly has no children type FieldProps = PropsWithoutChildr
Find elsewhere
๐ŸŒ
Total TypeScript
totaltypescript.com โ€บ react-component-props-type-helper
ComponentProps: React's Most Useful Type Helper | Total TypeScript
May 29, 2023 - Refs in React let you access and interact with the properties of an element. Often, it's used with form elements like inputs and buttons to extract their values or set their properties. The ComponentPropsWithRef does exactly what it says - provide the component props with its associated ref. ... In the example above, the InputProps type extracts the props of the input element, including the associated ref. Want more TypeScript knowledge?
๐ŸŒ
DEV Community
dev.to โ€บ bytebodger โ€บ default-props-in-react-typescript-2o5o
Default Props in React/TypeScript - DEV Community
July 29, 2020 - Specifically, it will use TypeScript & React. (Umm... OK. I got some learnin' to do.) I've been wanting to get my feet wet in a TS project for awhile. So I've been diving in eagerly. But in the last week-or-so, something really threw me for a loop. To illustrate the issue, I'm gonna take something from a plain-ol' JS component, and convert it into a TS component. The stub of my JS component looks like this: export default function MyJSComponent(props) { return ( <> Here is MyJSComponent:<br/> {props.children} </> ); } MyComponent.propTypes = { requiredString: PropTypes.string.isRequired, requiredNumber: PropTypes.number.isRequired, optionalBoolean: PropTypes.bool, optionalString: PropTypes.string, optionalNumber: PropTypes.number, }; MyComponent.defaultProps = { optionalBoolean: true, optionalString: 'yo', optionalNumber: 42, };
๐ŸŒ
Cinthialandia
cinthialandia.com โ€บ blog โ€บ props
What are props in react and how to use them with typescript? | Cinthialandia
We need to add the interface for the child component Children we declared the function onChange and add the syntax to the functional component for typescript. As you can see in this example we are not doing any changes for the parent component because the component its receiving the information by a callback but sending this function as a props. ... import React from "react" import "./style.css" interface Props { onChange: (n: string) => void } const Children: React.FC<Props> = ({ onChange }) => { const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { onChange(e.target.value) } return ( <div> <label>name</label> <input type="text" id="fname" name="fname" onChange={handleChange} /> </div> ) } export default Children
Top answer
1 of 5
574

2019: noticed all answers above are quite outdated so here is a fresh one.


Lookup type

With newer TS versions you can use lookup types.

type ViewProps = View['props']

Despite being very convenient, that will only work with class components.


React.ComponentProps

The React typedefs ship with an utility to extract the type of the props from any component.

type ViewProps = React.ComponentProps<typeof View>

type InputProps = React.ComponentProps<'input'>

This is a bit more verbose, but unlike the type lookup solution:

  • the developer intent is more clear
  • this will work with BOTH functional components and class components

All this makes this solution the most future-proof one: if you decide to migrate from classes to hooks, you won't need to refactor any client code.

2 of 5
41

Starting with TypeScript 2.8, you can use conditional types, e.g. given:

interface MyComponentProps { bar: string; }
declare const MyComponent: React.Component<MyComponentProps>;

interface MyComponentClassProps { bar: string; }
declare const MyComponentClass: React.ComponentClass<MyComponentClassProps>;

interface MyStatelessComponentProps { bar: string; }
declare const MyStatelessComponent: React.StatelessComponent<MyStatelessComponentProps>;

We can define these helpers:

type GetComponentProps<T> = T extends React.ComponentType<infer P> | React.Component<infer P> ? P : never

And use them like so:

// $ExpectType MyComponentProps
type MyComponentPropsExtracted = GetComponentProps<typeof MyComponent>

// $ExpectType MyComponentClassProps
type MyComponentClassPropsExtracted = GetComponentProps<typeof MyComponentClass>

// $ExpectType MyStatelessComponentProps
type MyStatelessComponentPropsExtracted = GetComponentProps<typeof MyStatelessComponent>

Update 2018-12-31: this is now available in the official React typings via React.ComponentProps.

๐ŸŒ
FullStack
fullstack.com โ€บ labs โ€บ resources โ€บ blog โ€บ typescript-react-component-interfaces-overloading-by-props
Scalable React Architecture with TypeScript | FullStack Blog
How do we infer our component interface from the value of our as property? To do this we can first define a function type interface. TypeScript allows us to create interfaces describing the shape and overloads of a function.
Top answer
1 of 3
9

I think you have a couple small issues in DisplayPerson.tsx. I've fixed them in this codesandbox: https://codesandbox.io/s/modest-snyder-s5bmt?file=/src/App.tsx

DisplayPerson.tsx:

import React from 'react';
import { Person } from '../App';

export default function DisplayPerson({ person }: { person: Person }) {
    return (
        <div>
            <h1>{person.firstName}</h1>
            <h1>{person.lastName}</h1>
        </div>
    );
}
  1. Your prop type is incorrect. Instead of { person }: Person you should have { person }: { person: Person }.
  2. You should wrap person.firstName and person.lastName with {}

To elaborate on #1: The props passed into DisplayPerson is an object where the key is the prop name and the value is whatever's passed in. Therefore, the type of the props object isn't Person but rather an object with key person and a value of type Person.

2 of 3
8

You need to correct your props part. So your DisplayPerson.tsx file will be like this

import React from 'react';
import { Person } from '../App';

interface IProps {
   person: Person
}
export default function DisplayPerson({ person }: IProps) {
    return (
        <div>
            <h1>{person.firstName}</h1>
            <h1>{person.lastName}</h1>
        </div>
    );
}

Update:

In React, the structure is like below for Functional component

function DisplayPerson(props) {}

as you see here props is a parameter that is of type object. so you need to pass an object. Now you want a person as a key inside that object which is Object deconstruction. That's why it has to be done like #1 from the answer of Nathan.
You can refer this: https://javascript.info/destructuring-assignment#object-destructuring

๐ŸŒ
Medium
eliya-b.medium.com โ€บ react-with-typescript-by-example-pass-props-to-children-6d37332ee434
React with Typescript by example, Passing Props to Children. | by Elia Bar | Medium
July 22, 2022 - yarn create react-app my-app --template typescript ... As you can see, children h1, button, and p of the Parent component are passed and used inside the Parent component with the help of childrenprop. We could pass any number and type of components in that way. Now letโ€™s build our Wizard component. ... A title prop in our interface, used at line 15.
๐ŸŒ
TypeScript
typescriptlang.org โ€บ docs โ€บ handbook โ€บ jsx.html
TypeScript: Documentation - JSX
As the name suggests, the component is defined as a JavaScript function where its first argument is a props object. TS enforces that its return type must be assignable to JSX.Element. ... Because a Function Component is simply a JavaScript function, function overloads may be used here as well: ... Note: Function Components were formerly known as Stateless Function Components (SFC). As Function Components can no longer be considered stateless in recent versions of react, the type SFC and its alias StatelessComponent were deprecated.
๐ŸŒ
GitHub
github.com โ€บ typescript-cheatsheets โ€บ react
GitHub - typescript-cheatsheets/react: Cheatsheets for experienced React developers getting started with TypeScript ยท GitHub
To access a DOM element: provide only the element type as argument, and use null as initial value. In this case, the returned reference will have a read-only .current that is managed by React. TypeScript expects you to give this ref to an element's ref prop:
Starred by 47K users
Forked by 4.3K users
Languages ย  JavaScript 93.9% | CSS 5.8% | Shell 0.3%
๐ŸŒ
Ben Ilegbodu
benmvp.com โ€บ blog โ€บ typescript-react-props-interfaces-type-aliases
TypeScript React props: interfaces vs type aliases | Ben Ilegbodu
November 13, 2021 - Let's take the example explained in the Conditional React props with TypeScript post where we have a Text component that allows for the text to be truncated with a truncate prop. And when the text is truncated there is also a showExpanded prop to include a "show expanded" button that will allow the truncated text to be expanded to the full text.