Skip to content

Instantly share code, notes, and snippets.

@timruffles
Last active June 15, 2017 09:34
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 timruffles/b0b214adc3ad6d3da4de9c74b467937c to your computer and use it in GitHub Desktop.
Save timruffles/b0b214adc3ad6d3da4de9c74b467937c to your computer and use it in GitHub Desktop.
string enums (ish, with some caveats) before ts 2.4
// 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