Skip to content

typescript can't infer destructuring of array properly  #32465

@deepkolos

Description

@deepkolos

TypeScript Version: 3.5.1

Search Terms: infer array destruction

Code

// A *self-contained* demonstration of the problem follows...
// Test this by running `tsc` on the command-line, rather than through another build tool such as Gulp, Webpack, etc.
function formatValue(value: string): [string, boolean] {
  const hasExpandString = /\%[^\%]*\%/i;
  return [value.replace(/^[\'\"].*[\'\"]$/, ''), hasExpandString.test(value)];
}

function formatOptions(options: string[]): [string, string, string, boolean] {
  let key, value, operator;
  switch (options.length) {
    case 2:
      [key, value] = options;
      return [key, '=', ...formatValue(value)]; 
      //                       ^
      // Type 'string | boolean' is not assignable to type 'string'.
      // Type 'false' is not assignable to type 'string'.
    default:
      throw new Error('argument error');
  }
}

Expected behavior: after destruction of array ts can infer [key, '=', ...formatValue(value)] to be [string, string, string, boolean] with formatValue(string): [string, boolean]

Actual behavior: got error
Type 'string | boolean' is not assignable to type 'string'.
Type 'false' is not assignable to type 'string'.

Playground Link: https://www.typescriptlang.org/play/index.html#code/GYVwdgxgLglg9mABMOAnAtgQygNUwGxAFMAKANwOIC5EBnKVGMAcwEoaBtexlgGkQBGcOPiKYwAXUQBvAFCJEEBPUQALTLQCiADwAO4gCYBlBk2aIAvIgD0AHQCkHAHoOJAKgfWYAbnmJURFAgqEgcFIREAHQBuviYEKTWThy2AOS2AEQSkW4p6VkAJNb8qams-OpaeoYmPMyRUET05JRErBK+AL6ysqCQsAjIaFhQAPK6A2C0JHAT8FM03GYcEuyIXKZ8dJvM-EtbQiJikjJ+olCIANZEAJ784cT8s0So2Gi+CrQA7jBQEKqIGZzZSRUQsKCqVinBQKCAaIiIABMVD8MPW1zuiAeRCkVlmk1oHzR-kCwVCGJKFlS-EitJQGGweAiLQi7SJsPhiAAzCjiejbk9dC83qh7q1cYh8fNCaiYTBgIDnq8oGhLBYrKkANSpRAAH11kqFytV6o1VNYsrRASCIX5mKVIppdOGjNaLOIbMtiCI+FoCIhqDgX0QYCIwc0qEDqBIqQdKtQgCvlQC-AYBrDUAmYqWfja1jsxAGIjATAgfBQXnEgNBkNhxARqMxwBDyoAHU3TgExUwD30WUid1OkA

Related Issues: #5296

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type
No fields configured for issues without a type.

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions