Skip to content

Instantly share code, notes, and snippets.

@asolove
Created April 20, 2016 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asolove/af897e918e31a657e481e7dd2993b11f to your computer and use it in GitHub Desktop.
Save asolove/af897e918e31a657e481e7dd2993b11f to your computer and use it in GitHub Desktop.
Flow sub/union typing
// Union types work as subtypes
type Animal = { legs: number }
type Person = Animal & { name: string }
function numberOfLegs(a: Animal): number {
return a.legs;
}
const p: Person = { legs: 2, name: "Adam" }
numberofLegs(p) === 2
// But a union of objects with the same key is not the same as an object with the union of those types
type Color = "green" | "red"
type AnimalHouse = { animal: Animal, color: Color }
type PersonHouse = AnimalHouse & { animal: Person }
function color(h: AnimalHouse): Color {
return h.color;
}
color({color: "green", animal: p})
// Found error: Property 'name' not found in object type 'Animal'.
// This seems to show it's trying to make Person and Animal the same
// Naively, I would assume a simplification like this:
// { a: B } & { a: C } => { a: B & C }
// Which then would type check?
// But I bet there's a good reason this isn't true.
// Can anyone enlighten me?
@asolove
Copy link
Author

asolove commented Apr 20, 2016

I think this is caused by Sealed object types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment