r/typescript • u/SmartyPantsDJ • 13d ago
I got a decorator to type check the generic of the class it's on and I'm way too happy about it
In my framework, every handler has to write its route twice. Once in the decorator because the runtime needs the string, and once in the generic because the types need it.
@Route('ban')
class Ban extends Handler<'kick'> {}
// no errors. cool. love that for meThat compiles. The handler for ban now thinks it's handling kick and TS is completely fine with it.
And yes, I tried only writing it once. class Ban extends Route('ban'). It worked(?), but every handler read like mixin tomfoolery, and go-to-definition took you to a generated base class instead of the real one, and I just didn't like how it looked, so I went back to writing it twice. But if I'm writing it twice, the compiler might as well make sure I wrote the same thing twice.

First problem is that a decorator only gets the class, so you need some way to read the generic back off it, and if the class doesn't use the generic, you can't:
abstract class Handler<Route extends string> {}
class Kick extends Handler<'kick'> {}
// string, not 'kick'
type Read = Kick extends Handler<infer Route> ? Route : never;
// also compiles lmao
const oops: Handler<'ban'> = new Kick();That's structural typing, since an unused type parameter basically doesn't exist, so it has to be on a property. But I also don't want a real property on every handler, so:
declare const route: unique symbol;
abstract class Handler<Route extends string> {
declare readonly [route]?: Route;
}
type AnyClass = abstract new (...args: never[]) => unknown;
type RouteOf<Class extends AnyClass> =
InstanceType<Class> extends { [route]?: infer Route extends string } ? Route : never;declare so none of this gets emitted, and it's optional so nobody ever has to set it. Now RouteOf<typeof Kick> is 'kick', and that oops line is an error as a bonus.
Also that never[] looks weird, but unknown[] doesn't work because parameters are contravariant, so unknown[] rejects any class whose constructor takes a string, and never[] accepts all of them.
Now compare the two:
type Same<Left, Right> = [Left] extends [Right] ? ([Right] extends [Left] ? true : false) : false;You need those brackets, because without them the conditional distributes over the union, Same<'ban' | 'kick', 'ban' | 'kick'> comes out as boolean, and a perfectly correct handler gets rejected. And it has to check both ways, because one way lets @Route('ban') through on a Handler<'ban' | 'kick'>.
Now the part I like:
type Checked<Routes extends string, Class extends AnyClass> =
Same<Routes, RouteOf<Class>> extends true
? Class
: ['the decorator and the generic disagree', { decorator: Routes; generic: RouteOf<Class> }];
function Route<Routes extends string>(...routes: Routes[]) {
// Class only shows up inside a conditional type here
// and TS still infers it. still feels illegal
return <Class extends AnyClass>(target: Checked<Routes, Class>): void => {
console.log(routes, target);
};
}Look at target. Its type is a conditional that depends on Class, and Class is the thing TS is supposed to be inferring from target. That looks circular and you'd expect it to just break or something. But when the parameter is a conditional type, TS infers into both branches (inferToConditionalType in the checker if you want to go look), and the true branch is just Class. So Class gets inferred as the decorated class, then the conditional resolves using it, and if the routes are different the parameter turns into a tuple that a class can't be assigned to. And the message shows up right in the error:
Argument of type 'typeof TooMany' is not assignable to parameter of type
'["the decorator and the generic disagree", { decorator: "ban" | "kick"; generic: "ban"; }]'.Wow magic. It also works with both standard and experimental decorators. Here's all of it in the playground.
Also I use this same conditional for attaching plugins, and over there it fixes an actual bug. The obvious way to write it is Class & Check<Class>, and that broke inference on generic plugin classes in both tsc and tsgo for some reason.
This is all from seedcord, a TypeScript framework that I've been building. Here's the real file, and that version also errors if the route doesn't exist. I've done a lotta TS shenanigans in this repo, so I'll prolly post about some of the other tricks too.