Skip to content
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

Using ES6 def. values for React component gives type error #33027

Closed
egonm12 opened this issue Aug 22, 2019 · 4 comments
Closed

Using ES6 def. values for React component gives type error #33027

egonm12 opened this issue Aug 22, 2019 · 4 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@egonm12
Copy link

egonm12 commented Aug 22, 2019

React defaultProps will be deprecated in future releases (see PR). Therefore I want to use es6 default values.

TypeScript Version: 3.7.0-dev.20190822

Search Terms:

  • Use es6 default values in React functional component instead of defaultProps

Code
The React component

import React from "react";

MyComponentProps {
  name: string;
}

export const MyComponent = ({ 
  name = "Jack" 
}: MyComponentProps) => (
  <div>
    <p>
      Hello {name}
    </p>
  </div>
)

The place where I use it

import React from "react";
import { MyComponent } from "./components"

const MyApp = () => <MyComponent />
TS2741: Property 'name' is missing in type '{}' but required in type 'MyComponentProps'

Expected behavior:
No type error as the default value is already defined

Actual behavior:
Typescript says that property is missing.

@RyanCavanaugh RyanCavanaugh added the Working as Intended The behavior described is the intended behavior; this is not a bug label Aug 22, 2019
@RyanCavanaugh
Copy link
Member

You declared the property as required, so it's required. If you want the property to be optional, mark it optional:

interface MyComponentProps {
  name?: string;
}

TypeScript will understand that the name parameter is always not undefined in the body of the function.

@egonm12
Copy link
Author

egonm12 commented Aug 22, 2019

Of course, that does make sense indeed. The strange thing however is that TypeScript doesn't complain when you use Component.defaultProps and leave the the name property in the interface required. That confused me.

@typescript-bot
Copy link
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

1 similar comment
@typescript-bot
Copy link
Collaborator

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

3 participants