flow icon indicating copy to clipboard operation
flow copied to clipboard

Indexer prevents property lookup on classes and interfaces

Open vkurchatkin opened this issue 9 years ago • 5 comments

Example:

declare class X {
  foo: string,
  [number]: number
};

declare var x: X;

x.foo; // ok
x[1]; // ok
x['foo']; // error

This works fine with object types.

vkurchatkin avatar May 24 '17 20:05 vkurchatkin

+1

aksuska avatar Mar 10 '18 21:03 aksuska

class Model {
 setKey(value: string | number): void {
    this[this.PRIMARY_KEY] = value
  }

  getKey(): string | number {
    return this[this.PRIMARY_KEY]
  }
}

Error: Cannot get this[this.PRIMARY_KEY] because an indexer property is missing in Model

moeen-basra avatar May 24 '18 20:05 moeen-basra

FYI that the fix for this currently is to extend the class with Object

declare class X extends Object {
  foo: string,
  [number]: number
};

bradennapier avatar Aug 20 '18 18:08 bradennapier

I faced a similar issue.

//@flow
type x = {y?: {[k:string]: string}}
let y: x = {'y':{'a': 'b'}}
let test = y.y !== undefined ? Object.keys(y.y).map(l=> y.y[l]) : null

Flow finds this to be invalid. Error message:

Cannot get y.y[l] because an indexer property is missing in undefined [1]

I circumvented this problem by making a redundant check.

if (y.y !== undefined){
    let test = Object.keys(y.y).map(l => {
        if (y.y!== undefined && l in y.y){ // y.y !== undefined is a redundant check
            return y.y[l]
        }
    })
}

Editing: I am sorry, I just realised that flow has mentioned this scenario in its documentation under the topic Type Refinement . The above behaviour is expected and should ideally be dealt this way.

//@flow
type x = {y?: {[k:string]: string}}

let y: x = {'y':{'a': 'b'}}

if (y.y !== undefined){
    const temp = y.y; // This is required because Object.keys could change the object y.
    let test = Object.keys(y.y).map(l => {
            return temp[l]
    })
}

manjunath-satyamurthy avatar Sep 05 '18 16:09 manjunath-satyamurthy

The workaround seems to have been murdered with [email protected]; see flow/try

Any updates on this issue/other workarounds that don't involve completely dropping the use of classes?

M-TGH avatar Sep 17 '18 07:09 M-TGH