Skip to content
Advertisement

Type json in React components

I have a dynamic json, for example:

{
    "first": "aaa",
    "second": "bbb",
    "other": "ttt"
}

And I created interface for this:

interface IResult {
    [key: string]: string;
}

I have two components:

function FirstComponent() {
    const [result, setResult] = useState<IResult>();

    useEffect(() => {
       setResult(some action);
    })

    return {
        <SecondComponent result={result}>
    }
}


function SecondComponent(result: IResult) {}

But this return me error:

Type “IResult” is not assignable to type ‘string’.

in line: <SecondComponent result={result}>

What I’m doing wrong?

Advertisement

Answer

When you pass arguments to a component, it is taken as props.

By defining SecondComponent as function SecondComponent(result: IResult) {}, you are declaring types of props as IResult and not the type of props.result as IResult.

Modify your declaration as following:

interface IProps {
 result: IResult
}

function SecondComponent(props: IProps) {}
Advertisement