Skip to content

Narrowed types do not flow into callback functions #44869

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
kolpav opened this issue Jul 2, 2021 · 1 comment
Closed

Narrowed types do not flow into callback functions #44869

kolpav opened this issue Jul 2, 2021 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@kolpav
Copy link

kolpav commented Jul 2, 2021

Bug Report

Previous discussion #37255 (comment)

Title is borrowed from @danielrentz #37255 (comment) I don't know if its accurate description of the problem.

πŸ”Ž Search Terms

None

πŸ•— Version & Regression Information

Any

⏯ Playground Link

Playground

πŸ’» Code

import { FunctionComponent, useMemo } from 'react'

export interface ButtonProps {
  size?: 'sm' | 'base' | 'lg'
}

export const Button: FunctionComponent<ButtonProps> = props => {
  props.size ??= 'base'
  const sizeClassNames = useMemo(() => {
    return {
      sm: 'px-3 py-2 text-sm',
      base: 'px-4 py-2 text-sm',
      lg: 'px-4 py-2 text-base'
    }[props.size] // << Type 'undefined' cannot be used as an index type.(2538)
  }, [props.size])

  return (
    <button
      type="button"
      className={sizeClassNames}
    >
      Button text
    </button>
  )
}

πŸ™ Actual behavior

Type 'undefined' cannot be used as an index type.(2538)

πŸ™‚ Expected behavior

props.size should not be considered as undefined

@MartinJohns
Copy link
Contributor

MartinJohns commented Jul 2, 2021

Another duplicate of #9998.

Besides that: Isn't it a big rule in React that components should not modify the props?

@sandersn sandersn added the Duplicate An existing issue was already created label Jul 2, 2021
@sandersn sandersn closed this as completed Jul 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants