3
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.

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.