When using Object as maps, Object.values treats values as mixed
I'm using objects as maps in the example below. It appears the type of Object.values is an array of mixed as opposed to an array of the Point type I defined.
type Point = {
x: number,
y: number,
};
type PointMap = { [key:string]: Point }
const foo: PointMap = { "1": { x: 5, y: 6}, "2": { x: 7, y: 8} };
Object.values(foo).map(p => {
return p.x;
})
It appears if I do use Object.keys instead, flow can correctly infer the type of foo[key]
Object.keys(foo).map(key => {
return foo[key].x;
})
This seems like a bug in flow, as we use Object as a map here and the type checker has enough info to correctly infer the type of Object.values(). Yes?
Why does Object.values return Array<mixed> currently?
At the moment, if you have a variable obj with the type { foo: string }, what does that mean? It means that obj.foo has the type string. But it doesn't mean that obj only has a single property. There may be other properties. This is because we let you write code like this:
function foo(obj: { foo: string, bar: number }) : { foo: string } {
return obj;
}
Allowing subtypes to have fewer properties than super types makes structural subtyping with object types work well. But it means when you write Object.values(obj), we can't say with certainty what types are in the resulting array.
How do I specify an object with ONLY certain properties?
As of v0.30.0, there is no way. However, @bhosmer is here to save the day! He's in the middle of landing the $Exact magic type. $Exact<{foo: string}> is the type of an object who has exactly one property named foo that is a string.
How does this help with Object.values?
Building on top of this, @samwgoldman is updating the types of Object.{entries,keys,values} to offer better types when used with exact types. So Object.keys(obj) should return Array<'foo'> when obj has the type $Exact<{foo: string}>. This might make v0.31.0, but if it doesn't it will definitely make v0.32.0.
I think this and https://github.com/facebook/flow/issues/2174 are duplicates.
@gabelevi Does what you're saying apply for map types, though? It seems like maps don't have this issue? As in the following gives me a type error on a:
const a: {[key: string]: string} = {b: 3};
const b: {a?: string} = {b: 3};
Could this just be a matter of adding an overload for the case where the argument to Object.values or Object.entries is a map type?
Having this exact same problem right now.
Use case:
// types.js
export type FieldLabel =
'SOME_FIRST_LABEL'
| 'SOME_SECOND_LABEL'
// ...
;
// constants.js
import type { FieldLabel } from './types';
export type FieldLabels = { [key: FieldLabel]: FieldLabel };
export const FIELD_LABELS: FieldLabels = Object.assign({}, ...[
'SOME_FIRST_LABEL',
'SOME_SECOND_LABEL',
// ....
].map(label => ({ [label]: label })));
// elswhere, someFile.js
import type { FieldLabel } from '../types';
import { FIELD_LABELS } from '../constants';
const fieldLabels: Array<FieldLabel> = Object.values(FIELD_LABELS).sort();
Results in: string enum This type is incompatible with (:0:1,0) mixed (/private/tmp/flow/flowlib_28d43509/core.js:52:39,43) [javascript/flow]
Another simple reproducible case: https://flowtype.org/try/#0PQKgBAAgZgNg9gdzCYAoVAXAngBwKZgAKMAhgMYEC8YA3qmGAG4kwCueAXGAM4YBOASwB2Ac1QBfdNnxFSFAMLkAFlVr0wAbQEATLr0GiAul2Lk8E9GThDeRADIBBeQFEA+vKcAJZybl5FZCpg1DTiANyW1rbMbKoA5Bh4vHERqISOLu5ezhoJSRhxhsG0TCzsXHFQcHBxYOHoAPIARgBWeGQYAHQx7NwAFOlObh7y3gCUnVDC2n19OH6+ZmOLFMEAfGoMW3x4GKx8QmDzZt1lVJTUPXgR4mNhQA
Another very simple reproducible case, just in case it helps: https://flowtype.org/try/#0PQKgBAAgZgNg9gdzCYAoALgTwA4FMwCSAJmALxgDO6ATgJYB2A5gNwY74Byc6tUtAxgEMecemTABvVGDC0iALkJEANNLABbXBQqDGuRVTpNVAX1Zs8YAMrph+cgBIAogA9B-dAB4JAbQDWuJiKxAC6ilw8fEIi9CYAfOb8olSUtuj61mn2kmaoqEn0KfTcvALCtKLhJVHlouISsgpgAOQAjM3KGlo6eorNcLTNYLlUdj7FkWUxAHRyIeITpdEV9InJ6GCLNTEUVZPLoj7z5ADyAEYAVrge0wBugjAArloAFKPpAJSsQA
I gave using $Exact<> an attempt here but looks like I might be using it wrong?
When I try to use exact notation to map
/* @flow */
const a: {|[string]: string|} = {'a': '1'};
const values: Array<string> = Object.values(a);
I get these errors
3: const a: {|[string]: string|} = {'a': '1'};
^ property `a`. Property not found in
3: const a: {|[string]: string|} = {'a': '1'};
^ object type
4: const values: Array<string> = Object.values(a);
^ string. This type is incompatible with
[LIB] static/v0.42.0/flowlib/core.js:52: static values(object: any): Array<mixed>;
^ mixed
Can you please tell me
- Why does exact notation not working with Object.values in this case?
- Why is it not possible to declare some variable as object map and then assign an object literal to it?
Type declarations like {|[string]: string|} are not really useful. Exact implies that all properties are known in advance.
@vkurchatkin Yes, that makes sense. But what how to deal with Object.values returning Array<mixed> for {[string]: string}?
How the below should be written? Even when everything is exact, that doesn't work with 0.45.0
type Thing = {|name: string, b: number|};
type Things = {|[id: string]: Thing|};
const getSortedArray = (things : Things) => Object.values(things).sort((a, b) => a.name.localeCompare(b.name));
what we get:
216: const getSortedArray = (things : Things) => Object.values(things).sort((a, b) => a.name.localeCompare(b.name));
^^^^ property `name`. Property cannot be accessed on
216: const getSortedArray = (things : Things) => Object.values(things).sort((a, b) => a.name.localeCompare(b.name));
^ mixed
This is causing headache too often.
Any solution for this? Running into this all afternoon :(
Just hit this too :(
for (const [key, value] of Object.entries(obj)) { } is a very common code pattern that's really messed up by this.
I've resorted to disabling flow on affected lines :(
The reason this isn't supported was explained pretty simply by @vkurchatkin in my (now closed) PR:
Here is a simple example:
function test(val: { foo: string }) { Object.values(val).forEach(v => { v.toLowerCase(); }); } test({ foo: 'x', bar: 123 });This going to pass typechecking, but fail at runtime
My PR would've set the following function type signatures for Object.entries, Object.values, and Object.keys, but was closed after it was pointed out how unsound these are:
- static entries(object: any): Array<[string, mixed]>;
+ static entries <T> (o: { +[s: string]: T }) : Array<[string, T]>;
+ static entries <T> (o: Array<T> | $ReadOnlyArray<T>) : Array<[string, T]>;
+ static entries (o: any) : Array<[string, mixed]>;
+ static keys <T> (o: { +[key: T]: any }): Array<T>;
static keys(o: any): Array<string>;
- static values(object: any): Array<mixed>;
+ static values <T> (o: { +[s: string]: T }) : Array<T>;
+ static values <T> (o: Array<T> | $ReadOnlyArray<T>) : Array<T>;
+ static values(o: any): Array<mixed>;
@jcready that's not the case with exact types where we know exactly what the object contains. see my comment above https://github.com/facebook/flow/issues/2221#issuecomment-303359174
It's not been only once or twice when someone in our dev team has spent way too much time figuring out what's wrong with their flow typings when this has been the reason. supporting exact types would help a bit.
~~I think the above definitions are almost correct, but the object-as-map version should be replaced with this:~~
~~static values<T, O : { +[string] : T }>(val : $Exact<O>) : Array<T>;~~
~~(and likewise for keys and entries).~~
~~I'd love to provide a patch myself, but I currently don't have time to get the flow build working. I might give it a shot later this week, if no-one else took it before me.~~
EDIT: this definition is also incorrect, as @jcready pointed out
In a comment on another issue, @samwgoldman mentioned that support for better object-as-dictionary typings on exact objects was already his top priority. I think this issue might be closable since his work on that is already underway.
Let's close it when it's actually fixed :P
@villesau @TiddoLangerak the problem is that indexers in exact object types don't work as you'd expect (at least right now):
declare class Obj {
static values <T> (o: {| +[s: string]: T |}) : Array<T>; // exact object w/ indexer
}
function test(val: {| foo: string |}) { // exact object w/o indexer
Obj.values(val).forEach((v) => {
v.toLowerCase();
});
}
test({ foo: 'bar' });
This results in the following error:
6: Obj.values(val).forEach((v) => {
^ property `foo`. Property not found in
2: static values <T> (o: {| +[s: string]: T |}) : Array<T>;
^ object type
Alternatively if we use @TiddoLangerak's definition for values:
static values<T, O : { +[string] : T }>(val : $Exact<O>) : Array<T>;
Then type-at-pos reports that the v parameter inside the forEach function is (unknown).
Unrelated, but @asolove I really wish the flow team would stop closing issues before they've actually fixed the issue. There seems to be an odd treatment of issues in this repo where they will be closed when the issue has simply been triaged or someone says they are going to make said issue a priority. Issues should be referenced in commit/PR messages so they can be closed automatically when the code actually gets merged to master.
You're right, I completely missed that v became untyped 😞
Is anyone looking at resolving this?