flow icon indicating copy to clipboard operation
flow copied to clipboard

Union subset still not working when it's a subset of a sentinel type

Open zgao opened this issue 10 years ago • 2 comments

/* @flow */

type Subset = 'a' | 'b';

type A = {
  sentinel: 'a';
};

type B = {
  sentinel: 'b';
};

type C = {
  sentinel: 'c';
  contents: string;
};

type Fullset = A | B | C;

function foo(bar: Subset): Fullset {
  return ({
    sentinel: bar
  });
}

This fails to typecheck, but it should. Here's the error which shouldn't exist:

test.js:21
 21:   return ({
               ^ object literal. This type is incompatible with
 20: function foo(bar: Subset): Fullset {
                                ^^^^^^^ union: A | B | C

zgao avatar Dec 17 '15 20:12 zgao

I believe it's the same issue as https://github.com/facebook/flow/issues/1014. Of course, it would be nice to hear from the developers on whether they plan to fix this in a foreseeable future...

pasha-mf avatar Dec 17 '15 22:12 pasha-mf

@zgao This is working as intended. Unfortunately without an assurance that sentinel is read-only, we cannot conclude that { sentinel: 'a' | 'b' } is the same as { sentinel: 'a' } | { sentinel: 'b' }.

function gen(sentinel: 'a' | 'b') {
  const obj = { sentinel };
  sub(obj, () => { 
    obj.sentinel = 'b';
  });
}

gen('a');

function sub(obj: { sentinel: 'a' } | { sentinel: 'b' }, callback: () => void) {
  if (obj.sentinel === 'a') fix(obj, callback);
}

function fix(obj: { sentinel: 'a' }, callback: () => void): {
  callback();
  (obj.sentinel: 'a');
}

avikchaudhuri avatar Jun 01 '16 10:06 avikchaudhuri