facebook / flow

Adds static typing to JavaScript to improve developer productivity and code quality.
https://flow.org/
MIT License
22.07k stars 1.85k forks source link

typeof loosing type information #5604

Open villesau opened 6 years ago

villesau commented 6 years ago

See this example

/* @flow */

const shape1 = Object.freeze({
    A: 'value1'
});

const shape2 = Object.freeze({
    A: 'othervalue'
});

//SHOULD FAIL since A differs!
(shape1: typeof shape2);

shape1 matches to typeof shape2 even though the values are totally different. All the objects are frozen. We are not able to type check our static object structures because of this. This is pretty bad and allows the developer to pass any string in without error. The worst thing is that it's not obvious for developer that this happens, flow does not tell anything about missing type information.

AugustinLF commented 6 years ago

If I recall correctly, typeof doesn't turn strings into enum, so here typeof shape1 === { A: string}. That's a know problem that has been raised several times (it's a problem for redux-like constants).

jcready commented 6 years ago

The only workaround right now is to annotate each property value (e.g. duplication)

const shape1 = Object.freeze({
  A: ('value1': 'value1')
});

const shape2 = Object.freeze({
  A: ('othervalue': 'othervalue')
});

(shape1: typeof shape2); // flow error