Skip to content

Instantly share code, notes, and snippets.

@imhoffd
Last active December 31, 2016 21:58
Show Gist options
  • Save imhoffd/dd11fb65472a159a77638ab4dda1062e to your computer and use it in GitHub Desktop.
Save imhoffd/dd11fb65472a159a77638ab4dda1062e to your computer and use it in GitHub Desktop.
class A { a: string }
class B { b: string }
// Tair's example.
let z = [new B(), new A()]; // z is inferred as array type of A | B
let [a1, b1] = z; // a1 and b1 are of type A | B
let x1 = a1.a + b1.b; // won't work (a1 could be of type B, b1 could be of type A)
let x2 = a1.b + b1.a; // won't work (a1 could be of type A, b1 could be of type B)
// Fixed
let y: [B, A] = [new B(), new A()]; // z is explicitly typed as 2-tuple of type [B, A]
let [a2, b2] = y; // typescript knows y[0] is of type B, y[1] is of type A
let x3 = a2.b + b2.a; // works as expected
let x4 = a2.a + b2.b; // won't work (a2 is of type B, b2 is of type A)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment