Typescript: Supposedly uninitialised default object destructing value in case where that value is obviously known

Created on 16 Jan 2020  路  2Comments  路  Source: microsoft/TypeScript

TypeScript Version: 3.7.2 (any version in reality)

Search Terms: Initializer provides no value for this binding element and the binding element has no default value

Code

// This simulates a situation where function's param can be either a string, or an options object with that string as one of the values
const stringOrObjectParam = Math.random() > .5 ? 'string param' : { baz: 'object param' }

const isStringParam = (param: string | {}): param is string => typeof param === 'string'

// One of the typical ways in JS to provide default values
const { foo, bar } = {
  bar: 'default value',
  ...(isStringParam(stringOrObjectParam) ? { foo: stringOrObjectParam } : stringOrObjectParam),
}

Expected behavior: No error (bar is always known as either derived from stringOrObjectParam or being 'default value').

Actual behavior: Error: Initializer provides no value for this binding element and the binding element has no default value. for bar in const { foo, bar } = {

Playground Link: https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=8&pc=2#code/MYewdgzgLgBNBOBLMBzA8vNAjAVgU2CgAUBDeEgWxgF4YBZEqACwDpywATECgCgEoYAPhgsArDAD8MAOQJkMAA5lK0mAC4YAbxhYSALw3SQuArCXkKqgL4AoG6EixEEAMpQkqUhZowe5yhpyqDAAPlpWfBr+VM5w7sgoNMJQAJ4KeCAAZorKVNT5MkEo0nYO0FowmSAgADQ6ZDBWPpo2MPXwhhx4mSQArgA2sABuJP29eNI1rSIsLDzObh4oXpQ8RRjY+IQrFAJS2lUggfGoGybbuY3qcUtnW8S5fFNWQA

Related Issues: There are a lot of issues that report this error as a bug, in which it's proved that bug it was not. In this case, however, I don't see how bar could be considered uninitialised.

Bug Fix Available

Most helpful comment

const { foo, bar } = {
  bar: 'default value',
  ...({foo: 10}),
}

All 2 comments

I think the type of bar in this case is any (cause stringOrObjectParam being an object can have anything under the bar key) but it's still different than throwing an error.

const { foo, bar } = {
  bar: 'default value',
  ...({foo: 10}),
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

Antony-Jones picture Antony-Jones  路  3Comments

bgrieder picture bgrieder  路  3Comments

manekinekko picture manekinekko  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

siddjain picture siddjain  路  3Comments