1

I have a component with these props:

type Props = {
  items: {
    text: string;
    status?: "processing" | "error" | "info-required";
  }[];
};

const Component: React.FC<Props> = ({ items }) => 

When I use the component and set the props inline it works fine:

<Component
    items={[
      { text: "a" },
      { text: "b" },
      { text: "c", status: "processing" }
    ]}
  />

However when I put the props in an object it errors:

const items = [
  { text: "a" },
  { text: "b" },
  { text: "c", status: "processing" }
]

<Component items={items} />

Types of property 'status' are incompatible. Type 'string' is not assignable to type '"error" | "processing" | "info-required"'.

The expected type comes from property 'items' which is declared here on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'

3
  • 2
    Typescript is probably guessing that the type of status in the items variable is string. If you copy the type of the items property in Props over, it'll work. E.g. try const items: typeof Props['items'] = ... Commented May 27, 2020 at 15:52
  • @cbr good thinking :) There is no need for the keyword typeof thought, because Props['items'] already reference { text : string, status ?: '...' } Commented May 27, 2020 at 16:00
  • 1
    @GrégoryNEUT Good catch! I did not even realize that before I read your answer. Commented May 27, 2020 at 16:01

1 Answer 1

1

The thing is, because you haven't defined the type of const items, typescript is not sure that status will always contain something compatible with the type "processing" | "error" | "info-required".

For example, you could do, items[2].status = 'invalid text';

You should ensure the type of items like : const items: Props['items']


enter image description here

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.