Reputation: 1359
TypeScript allows marking generics at the method level to constrain the type of one parameter based on the type of another parameter.
class Publisher {
publish<K extends keyof Channels>(channel: K, payload: Channels[K]) { }
}
However, it seems that TypeScript does not support this for the constructor
type Events = {
CastSpell: { caster: string, spell: string },
Attack: { attacker: string, defender: string },
}
class Achievement {
constructor<K extends keyof Events>( // Error
public name: string,
protected eventLabel: K,
protected requirement: (eventData: Events[K]) => boolean
) { }
}
const achievement = new Achievement(
'Your first fireball!',
'CastSpell',
(event) => event.spell == 'Fireball' // Error
)
Type parameters cannot appear on a constructor declaration.ts(1092)
Argument of type '"CastSpell"' is not assignable to parameter of type 'K'.
'"CastSpell"' is assignable to the constraint of type 'K', but 'K' could be
instantiated with a different subtype of constraint 'keyof Events'.ts(2345)
I could mark the generic at the level of the class, but the constraint I'm attempting to impose is only relevant to the construction of the object rather than an overarching aspect of the class, so a method level generic feels more appropriate.
Is there a way to achieve this? Is there a reason why this is not supported directly?
Upvotes: 1
Views: 102