3

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

Tomasz Waszczyk
  • 2,680
  • 5
  • 35
  • 73
  • Your component expects `name` to be of type `string` but the value you are passing is of type `string | null`. – chautelly Dec 07 '20 at 13:44

1 Answers1

5
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} />
Frenco
  • 1,299
  • 1
  • 8
  • 25
  • 1
    Alternatively you can also cast to a string like this: `query.get("name")!` by adding an exclamation mark. See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator – chautelly Dec 07 '20 at 14:35