Tomasz Waszczyk
Tomasz Waszczyk

Reputation: 3159

Binding element 'string' implicitly has an 'any' type

I have such kind of code:

function Child( { name: string } ) {
  return (
    <div>
      {name ? (
        <h3>
          The <code>name</code> in the query string is &quot;{name}
          &quot;
        </h3>
      ) : (
        <h3>There is no name in the query string</h3>
      )}
    </div>
  );
}

and I got:

enter image description here

I was trying in many ways to pass name name literal but TypeScript always complays, any idea how to make happy TypeScript?

The code is taken from: https://reactrouter.com/web/example/query-parameters

Upvotes: 3

Views: 4183

Answers (1)

user7720975
user7720975

Reputation:

function Child(name: { name: String}) { ...
/// ^ this is not typing the props, 
/// it's typing the first parameter called name

To properly type the React props, you gotta do this.

function Child({name}: {name: string}) { ...

You might also want to use the type string instead of wrapper String as they are not the same thing. It is recommended to use string when possible. Check this question out for more info on that.

Also according to the error, the query.get("name") function is returning a nullable string. You might want to cast it before using it to make sure it's not null.

<Child name={query.get("name") as string} />

Upvotes: 5

Related Questions