Indexer prevents property lookup on classes and interfaces
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.
+1
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
FYI that the fix for this currently is to extend the class with Object
declare class X extends Object {
foo: string,
[number]: number
};
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]
})
}
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?