Skip to content

Array Destructuring Inference Is Incorrect #36635

@Skillz4Killz

Description

@Skillz4Killz

Search Terms

array destructuring, array destructuring inference

Suggestion

When you use array destructuring the type is inferred incorrectly. I hope something can be changed to enforce proper type inference when using this. In my code, TS has helped clean and prevent a lot of mistakes. The only mistakes that I repeatedly find being made either by me or others in my project are always related to this. Time and time again I have had these errors happen in runtime making the benefits of Typescript lost. An option to enforce this would be amazing, please. (Especially if it is just included inside the strict option.)

Use Cases

const example = (args: string[]) => {
  const [userID, duration, ...reason] = args
  // userID and duration is AUTOMATICALLy inferred to be a string here. 
 // However, if for whatever reason args is an empty array userID is actually `undefined` and NOT a `string`. 

// This is valid but it should not be because userID could be undefined
userID.toUpperCase()
}

Examples

const example = (args: string[]) => {
  const [userID] = args
  // userID is AUTOMATICALLy inferred to be a string here. 
 // However, if for whatever reason args is an empty array userID is actually `undefined` and NOT a `string`. 

// Typescript SHOULD warn that this is not possible on undefined
userID.toUpperCase()
}

Proper Way:

const example = (args: string[]) => {
  const [userID, duration, ...reason] = args
  if (!userID) return

  // This is valid but it should not be because userID could be undefined
  userID.toUpperCase()
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions