Francis Bourre
Francis Bourre

Reputation: 268

TypeScript compiler doesn't complain with this generic constraint

class Stub
{

}

interface IListener<T>
{
    method( e : Event<T> ) : void;
}

class Event<T>
{
    target : T;
}

class Listener implements IListener<Stub>
{
    method( e : Event<boolean> ) : void
    {

    }
}

Is there any reason why TS compiler doesn't complain ? 'boolean' violates the interface contract. Stub type is specified in the implementation.

Upvotes: 3

Views: 82

Answers (2)

basarat
basarat

Reputation: 276353

This is because TypeScript is structurally typed. The following works (which is a simplification of your code sample:

class Stub
{

}

let foo:Stub = true; // Allowed ... `boolean` has all the member that a Stub has 

However the following will fail:

class Stub
{
    someMember: string;
}

let foo:Stub = true; // Error. A boolean doesn't have `someMember` which should exist on a `Stub` 

The reason for this is developer convenience.

Here is more discussion : http://basarat.gitbooks.io/typescript/content/docs/why-typescript.html

Upvotes: 2

Torsten Franz
Torsten Franz

Reputation: 11

I guess it is due to the fact your Stub class does not expect anything which is fulfilled by basically every other type (incl. your boolean example). If you add e.g. x:number to your stub it will be flagged as error then.

Upvotes: 0

Related Questions