microsoft / microsoft/TypeScript

Control flow doesn't affect spreaded properties

Open
#36,702 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Control Flow
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.7.4

Search Terms: react required props

image

Code

import React from 'react'

type Props = {
  foo?: string
}

const Example = (props: Props) => (
  <>
    {/* [bug?] Throws an error about required prop, despite null check */}
    {props.foo && <Component {...props} />}


    {/* Shows an error, as expected, because lack of null-check  */}
    <Component {...{ ...props, foo: props.foo }} />

    {/* Workaround 1: No error */}
    {props.foo && <Component {...{ ...props, foo: props.foo }} />}


    {/* Shows an error, as expected, because lack of null-check  */}
    <Component {...props} foo={props.foo} />

    {/* Workaround 2: No error */}
    {props.foo && <Component {...props} foo={props.foo} />}
  </>
)

const Component = ({ foo }: Required<Props>) => <p>{foo}</p>

export default Example

Expected behavior:

TypeScript would detect that we're inside a null check, and treat the checked property as non-nullish.

Actual behavior:

TypeScript doesn't notice that the checked property is non-null, because it's inside an object spread.

As a workaround, the null-check will still work if the property is explicitly added to the spread object (workaround 1) or explicitly passed as a prop (workaround 2).

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the provided TSX example with TypeScript 3.7.4 and compare the spread cases with the explicit-property workarounds. Trace the compiler's control-flow analysis for JSX object spreads, then add regression coverage showing that the checked property is treated as non-nullish through the spread.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.