Why is TypeScript telling me "Type '{ walletAddress: string; }' is not assignable to type 'string'.ts(2322)" even though I am passing a string?

Viewed 43

I am a bit of a TypeScript newbie in React. Constructing the start of a component is still unfamiliar to me. So I think I am building my Address component wrong.

I am trying to pass a string as a prop to a component. It should be simple but something's going awry.

I have an Address component defined in React:

const Address = (walletAddress: string) => {
    return (
        <div className="mb-10"> {walletAddress} </div>
    )
}

And I pass a prop to it:

<Address walletAddress={publicAddress}/>

Under <Address there is a red squiggly saying "Type '{ walletAddress: string; }' is not assignable to type 'string'.ts(2322)"

I don't understand why this is happening. Console log of publicAddress is a string. So I am passing a string into something that is supposed to be a string, yet it yells at me.

What's up with this?

My expected behavior is that I pass the string value publicAddress into walletAddress and it shows up in the Address component.

Edit: console.log of walletAddress is an object {walletAddress: '0x3a01...af'} which is not what I expect from the argument

2 Answers

Your Address component is receiving props as every React component. props is an object, not a primitive string.

You should change it to something like this:

    const Address = ({ walletAddress}: { walletAddress: string}) => {
        return (
            <div className="mb-10"> {walletAddress} </div>
        )
    }

You can also create interface for defining prop type

    import type { FC } from 'react';
    
    interface AddressProps {
      walletAddress: string;
    }
    
    const Address: FC<AddressProps> = ({walletAddress}) => {
      return (
        <div className="mb-10"> {walletAddress} 
        </div>
      )
    }

Solution 1, made by investigating other peoples' code

type addressProps = {
    publicAddress: string
}

const Address = ({ publicAddress }: addressProps) => {
// ...
}

I don't understand why I had to do it that way but it works

Related