Last active
June 15, 2017 09:34
-
-
Save timruffles/b0b214adc3ad6d3da4de9c74b467937c to your computer and use it in GitHub Desktop.
string enums (ish, with some caveats) before ts 2.4
This file contains 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
// cast the strings as any | |
enum StringEnum { | |
a = 'a' as any, | |
b = 'b' as any, | |
} | |
const a = StringEnum.a; | |
const x = 'a'; | |
const y = 1; | |
const fn = (x: StringEnum) => 1; | |
// type error: Argument of type "a" is not assi... | |
fn(x) | |
fn('z') | |
// weirdly, no type error | |
fn(1) | |
fn(10) | |
// ok | |
fn(a) | |
// but can't narrow | |
class A { | |
type = StringEnum.a; | |
propA = true; | |
} | |
class B { | |
type = StringEnum.b; | |
propB = true; | |
} | |
type C = A | B; | |
function aOrB(c: C) { | |
if(c.type === StringEnum.a) { | |
// error - type B has no property propA | |
return c.propA; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment