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

Default values of object destructuring of Generic type #30628

Closed
Pomar81 opened this issue Mar 28, 2019 · 5 comments
Closed

Default values of object destructuring of Generic type #30628

Pomar81 opened this issue Mar 28, 2019 · 5 comments
Labels
Duplicate An existing issue was already created

Comments

@Pomar81
Copy link

Pomar81 commented Mar 28, 2019

Hi, TypeScript Team

Version: 3.3.4

I have a problem with default values of destructed variables inside a generic function. If I don't specify type for destructuring construction I could set anything as default values.

type HeaderTypes = 'h1' | 'h2' | 'h3'

type HeaderProps<H extends HeaderTypes> = {
    abc?: H,
    className?: string,
}

const Header = <H extends HeaderTypes>(props: HeaderProps<H>) => {
    const { abc = 'h1' }: HeaderProps<H> = props;
   // ......
}  

Expected behavior:
abc can be assigned to 'h1'
Actual behavior:
TS2322:Type 'h1' is not assignable to type 'H'

Playground Link: example

@Pomar81 Pomar81 changed the title Destruction of Generic type Destructuring of Generic type Mar 28, 2019
@Pomar81 Pomar81 changed the title Destructuring of Generic type Default values of object destructuring of Generic type Mar 28, 2019
@jack-williams
Copy link
Collaborator

Essentially the same problem as: #29528 and #30157

@Pomar81
Copy link
Author

Pomar81 commented Mar 28, 2019

Hi @jack-williams
Yes. #29528 is very close. But is there any solution on how to fix my problem?

@jack-williams
Copy link
Collaborator

I don't understand your use-case fully but I would write something like:

const Header = <H extends HeaderTypes>(props: HeaderProps<H>) => {
    const { abc = 'h1' }: HeaderProps<H | "h1"> = props;
   // ......
}  

@Pomar81
Copy link
Author

Pomar81 commented Mar 28, 2019

In my current context, it is ok. Thank you.
But in general, it will be great to somehow eliminate this problem with Generic

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 28, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' 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
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants