Flow: Computed property cannot be assigned with String

Created on 4 Jul 2017  路  4Comments  路  Source: facebook/flow

Input:

function a (values: Array<String> = []) {
  return values.reduce(
    (acc, cur) => Object.assign(acc, { [cur]: cur }),
    {}
  );
}

Error:

3:     (acc, cur) => Object.assign(acc, { [cur]: cur }),
                                        ^ object literal. Computed property cannot be assigned with
3:     (acc, cur) => Object.assign(acc, { [cur]: cur }),
                                           ^ String

REPL

Similar issue: #3258

bug needs triage

Most helpful comment

workaround (string instead of String):

function a(values: Array<string> = []): { [string]: string } {
  return values.reduce(
    (acc, cur) => Object.assign(acc, { [cur]: cur }),
    {}
  );
}

(i've added the annotation for the return type too, because flow wasn't able to infer it)

All 4 comments

workaround (string instead of String):

function a(values: Array<string> = []): { [string]: string } {
  return values.reduce(
    (acc, cur) => Object.assign(acc, { [cur]: cur }),
    {}
  );
}

(i've added the annotation for the return type too, because flow wasn't able to infer it)

Is there any plan on adding this? It is quite bad that we can't use computed properties as keys ...

I think you shouldn't use String

This is happening for me with the ?boolean type even though my map contains values for true, false, and null, all 3 types a ?boolean can take.

export const selectedOptionMap = {
[true]: "Yes",
[false]: "No",
[null]: "Undo",
}
Error: src/actions/report.js:456
456:     selected_option: selectedOptionMap[isCorrect],
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ computed property. Computed property cannot be accessed with
456:     selected_option: selectedOptionMap[isCorrect],
                                            ^^^^^^^^^ boolean

Error: src/actions/report.js:456
456:     selected_option: selectedOptionMap[isCorrect],
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ computed property. Computed property cannot be accessed with
456:     selected_option: selectedOptionMap[isCorrect],
                                            ^^^^^^^^^ null

Error: src/actions/report.js:456
456:     selected_option: selectedOptionMap[isCorrect],
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ computed property. Computed property cannot be accessed with
456:     selected_option: selectedOptionMap[isCorrect],
                                            ^^^^^^^^^ undefined
Was this page helpful?
0 / 5 - 0 ratings