hegel icon indicating copy to clipboard operation
hegel copied to clipboard

Type "{ a: boolean }" is incompatible with type "{ a: false } | { a: true }"

Open thecotne opened this issue 5 years ago • 3 comments

type Data = { a: true } | { a: false }

function thisDoesNot(data: Data): Data {
  return {
    a: data.a
  }
}

try

thecotne avatar Apr 28 '20 09:04 thecotne

message has changed from Type "{ a: false | true }" is incompatible with type "{ a: false } | { a: true }" to Type "{ a: boolean }" is incompatible with type "{ a: false } | { a: true }"

i think change was introduced with this commit https://github.com/JSMonk/hegel/commit/95fdae84819b1f131110456f7e1a1f7aa2d39da1

thecotne avatar May 14 '20 20:05 thecotne

Yes. And I don't know how to fix it for now :( I'm about the issue. The issue exists in Flow Example. And doesn't exist in TypeScript Example. But with TypeScript, there is problem, because of type { a: false | true } equal to type { a: false } | { a: true }. And we easily can get the next error:

function process(a: { value: true } | { value: false }) {
  a.value = false;
}

const CONSTANT: { value: true } = { value: true };

process(CONSTANT);

Try

JSMonk avatar May 14 '20 22:05 JSMonk

@JSMonk that's how typescript's type assignment works there is no safety or soundness in it see https://github.com/microsoft/TypeScript/issues/33748

but i understand why it's complicated to implement

i think this should work as well (does not work in ts and flow)

type Data = { a: string } | { a: number }

function thisDoesNot(data: Data): Data {
  return {
    a: data.a
  }
}

try

editing of union object is different story for that you need to refine type to sub set of union objects that allow type of modification developer is intended to do for example

type Data = { a: string } | { a: number }

function notOk(data: Data) {
  data.a = 'sdsds'//err
}

function ok(data: Data) {
  if (typeof data.a === 'string') {
    data.a = 'sds'//ok
  }
  if (typeof data.a === 'number') {
    data.a = 111//ok
  }
}

thecotne avatar May 14 '20 22:05 thecotne