镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Object destructuring type doesn't narrow parameter B when parameter A is narrowed #44169

Description

Bug Report

🔎 Search Terms

destructuring
narrowing
is not assignable to type

🕗 Version & Regression Information

(todo)

  • This is a crash
  • This changed between versions ______ and _______
  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about _________
  • I was unable to test this on prior versions because _______

💻 Code

This works

type Dastructure = 
   {b: false, c: null} |
   {b: true, c: string}

class Example {
   prop?: string;
   constructor (options: Dastructure) {
      if (options.b) {
         this.prop = options.c
      }
   }
}

This gets an error

type Dastructure = 
   {b: false, c: null} |
   {b: true, c: string}

class Example {
   prop?: string;
   constructor ({b, c}: Dastructure) {
      if (b) {
         this.prop = c
//       ^^^^^^^^^
// Type 'string | null' is not assignable to type 'string | undefined'.
//   Type 'null' is not assignable to type 'string | undefined'.
      }
   }
}

🙁 Actual behavior

error

🙂 Expected behavior

not error?

I think it's because in the second code the context of {b, c}: A isn't considered when b is narrowed

Activity

  1. changed the title [-]Object destructuring for parameters don't narrow[/-] [+]Object destructuring type doesn't narrow parameter B when parameter A is narrowed[/+] on May 19, 2021
  2. RyanCavanaugh commented on May 19, 2021

    @RyanCavanaugh
    Member

    This is a duplicate but I want to reraise the idea of CFA-linking variables sourced from the same destructuring expression

  3. dhythm commented on May 21, 2021

    @dhythm

    I agree with this suggestion.
    Type inference doesn't work well when I use destructuring.
    I'm happy if this issue is solved. 🙏

    image

  4. remcovaes commented on Aug 9, 2021

    @remcovaes

    Is there any update on this? I am running into the exact same issue...

    type F = ({ foo, bar }: { foo: number, bar?: never } | { foo?: never, bar: true } ) => number;
    
    const f: F = ({ foo, bar }) => {
    	if (bar === true) {
    		return 2;
    	}
    
    	return foo;
    };

    https://www.typescriptlang.org/play?ts=4.3.5#code/C4TwDgpgBAYlC8UAUBvKAzA9pgNFARgIYBOUAvgFxRpaZUB2ArgLb4TF5HED8DEAbu3JQAPtQzZeUegPacSVYMUbQyUAJQIAfNJZtiAbgBQRgMaZ6AZ2AYqcRKgm4CJcpvg6URgJABLdMhcCPCISiqaXt7exBDAjMT0UABMxt5kJtGx8Ym0xmTGQA

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions