Skip to content

Spreading props in JSX on right hand side of && operator gives incorrect undefined warningΒ #48326

Closed as not planned
@samtjo

Description

@samtjo

Bug Report

πŸ”Ž Search Terms

Spread, Spreading, &&

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about prop spreading.

⏯ Playground Link

https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wG4AocmATzCTgGFdIA7JFmAeTYAUcwAznAC8cAN7k4cGMBgAbJAC44AmFGAsA5hQC+FcmggtVjZkfZc2IuAAox02Qrg7lTcOY7ckfCIICUIgB84pJwRDAArlAscAA8ABYAjIFiMvJIOrEA9EmBuvo0dKbubBwAKgDuED6C1hJSaQqVEAD8yqrqWvmUhsbwbqwWzdZ2DunDLsWD5VU1AgHCwfVwvSaGJRZec3WhDY5KY01VADSheqHhUTGNSMMAZHdxAx6W9GIAdJ-r069zOnBZPLkc7kJAAD0gsDgABMkJgUBE5P0zKUYM0KFksnAALLUFYQWFwTQQJBCeJIIhAA

πŸ’» Code

import React from "react";

type ComponentOneProps = {
  title: string;
};

const ComponentOne = ({ title }: ComponentOneProps) => {
  return <h1>{title}</h1>;
};

type ComponentTwoProps = {
  titleTwo?: string;
};

const ComponentTwo = ({ titleTwo }: ComponentTwoProps) => {
  const componentOneProps = {
    title: titleTwo,
  };
  return titleTwo && <ComponentOne {...componentOneProps} />;
};

export default ComponentTwo;

πŸ™ Actual behavior

image

Because we checking that titleTwo is truthy here (as it's the first operand of the logical AND operator) - the title prop of ComponentOne can never actually be set to undefined, but we get a warning saying type Type 'string | undefined' is not assignable to type 'string'.

πŸ™‚ Expected behavior

I would expect no error here, as the title prop can never be actually set to a falsey value on ComponentOne there. I think this may be an issue with spreading the props onto ComponentOne here as it works if you set the title prop directly:

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions