Created
April 20, 2016 15:17
-
-
Save asolove/af897e918e31a657e481e7dd2993b11f to your computer and use it in GitHub Desktop.
Flow sub/union typing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think this is caused by Sealed object types.