Skip to content

Instantly share code, notes, and snippets.

@mmis1000
Created July 1, 2018 18:34
Show Gist options
  • Save mmis1000/a4af5028c22b991903d2daeb3df4af97 to your computer and use it in GitHub Desktop.
Save mmis1000/a4af5028c22b991903d2daeb3df4af97 to your computer and use it in GitHub Desktop.
A test for type include and pattern match with typescript
interface Construcable<P> {
new(...arg:any[]): P
}
type InstanceOf<T, U = T extends Construcable<infer C> ? C: T> = U;
type ConstructorToType<T> =
T extends StringConstructor? string:
T extends BooleanConstructor? boolean:
T extends NumberConstructor? number:
T extends null? null:
T extends undefined? undefined:
InstanceOf<T>
class Switch<T, U> {
constructor() {}
run<V, W = V extends Case<infer X, U> ? ([Exclude<T, X>] extends [never] ? U : never) : never>(c: V): W {
return
}
}
class Case<T, U> {
constructor() {
}
case<V, W=ConstructorToType<V>>(c: V, cb: W extends T ? never: (arg: W)=>U): Case<T|W, U>{
return null;
}
}
var a: Case<never, number>;
var b = a.case(String, (a)=>10);
var c = b.case(Number, (a)=>10);
var d = c.case(Boolean, (a)=>10);
var e: Switch<number|string|boolean, number>;
var l = e.run(a).toString();
var l = e.run(d).toString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment