Jiří Lechner
Jiří Lechner

Reputation: 820

no compile error on a wrong type

Although defining a type of a function parameter the compiler doesn't give me a compile error when I pass in a wrong type.

class A
{
  constructor(public data: any)
  {}
};

class B extends A
{
  constructor(instance: A)
  {
    if (B.validate(instance.data))
      super(instance.data)
    else
      throw 'error';
  }

  static validate(instance: A): boolean
  {
    return typeof instance.data == 'number';
  }
}

let a = new A(null);
let b = new B(a);

The if (B.validate(instance.data)) line is wrong and I would expect an compiler error but it compiles fine.

Upvotes: 0

Views: 80

Answers (3)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220974

There's no error because data is declared as type any. Values of type any can be used anywhere without error, because that is the job of the any type.

Upvotes: 1

Matt McCutchen
Matt McCutchen

Reputation: 30889

instance.data is of type any, which is allowed to be passed where any type is expected. You'll need to give it a more specific type if you want a compile error.

Upvotes: 3

felixmosh
felixmosh

Reputation: 35503

If the signature of validate is from a type instance: A, then, You can't pass instance.data to it, you should pass instance instead.

Upvotes: -1

Related Questions