Makla Makla - 4 months ago 18
TypeScript Question

Force generics implements property in TypeScript (constrains on generics)

I want to force that generic implements property in TypeScript.
My current code is:

interface IEventHandler<TArgs>
{
(args: TArgs): void
}


interface ISubscribable<THandlerType>
{
bind(fn: THandlerType): void;

unbind(fn: THandlerType): void;
}

interface IEvent<TArgs> extends ISubscribable<IEventHandler<TArgs>>
{
}


Something like
interface IEventHandler<TArgs> where TArgs : has_property_sender
. I know where does not exists for TypeScript, so maybe I can get a workaround with another interface?

Is this possible in TypeScript?

Edited:

Code if it helps someone else. I don't know if it can be optimized.

TSV TSV
Answer

You can use constraints (section "Generic Constraints") in Typescript, e.g.:

interface has_property_sender {
    sender: Object;
}

interface MyArgs extends has_property_sender {
    property: Object;
}

interface IEventHandler<TArgs extends has_property_sender>
{
    (args: TArgs): void
}