0

I'm new to React and typescript.

I've found I need to declare props as such:

const Title = ({title}:{[key:string]:any}) => {

But this seems a bit convoluted to me. Is there a better way to go about this?

0

2 Answers 2

2

You can keep it simple, if you want, by declaring an interface with all the props you're expecting:

interface MyProps {
  A: string;
  B: number;
  C?: number; // C is optional
}

const MyComponent = ({ A, B }: MyProps) =>  { ... }
Sign up to request clarification or add additional context in comments.

Comments

2

I would suggest using the FC generic (which is an alias for the FunctionComponent generic). I prefer to use this as apposed to not using the generic because it appends the children property as well as types the return value from the functional component, React.Element vs JSX.Element.

import * as React from "react";
import {FC} from "react";

interface ITitleProps {
   title: string;
}

// This works as expected
export const Title1: FC<ITitleProps> = ({
    title,
    children // Added by 'FC'
}) => {
    return (
        <div>
            <h1>{title}</h1>
            <p>{children}</p>
        </div>
    );
};

// This produces an error
export const Title2 = ({
    title,
    children // property 'children' does not exist on type 'ITitleProps'
}: ITitleProps) => {
    return (
        <div>
            <h1>{title}</h1>
            <p>{children}</p>
        </div>
    );
};

This GitHub was invaluable trying to figure out how to use TS with React: React TypeScript Cheatsheet

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.