Typescript inheritance where datatypes in IntelliSense is any instead of expected number

109 Views Asked by At

I have a tiny code implementation in Typescript where I have a class either implementing an interface or extending a class.

interface ITest {
    run(id: number): void
}

abstract class Test implements ITest {

    abstract run(id);
}

class TestExtension extends Test
{
    constructor() {
        super();
    }

    public run(id) { }
}

class TestImplementation implements ITest {
    constructor() {

    }

    public run(id) { }
}

Both shows wrong Intellisense where I expected id to by of type 'number':

(method) TestExtension.run(id: any): void
(method) TestImplementation.run(id: any): void

I can of course set method implementation to be public(id: number) { } but I don't see why I have to do this.

Can someone enlighten me, please?

1

There are 1 best solutions below

1
basarat On BEST ANSWER

Your understanding of implements ITest is a bit in correct. TypeScript interface implementation is not like other langauges, it is purely a compile time contract static that members of the class must be compatible with the interface definition.

So like the following is correct:

let foo: number;
let bar; // inferred any 
foo = bar; 

the following is also correct

interface IFoo {
  foo: number
}
class Foo implements IFoo {
  foo; // Inferred any
}

The function argument is also any in your code without an explicit signature

Fix

Be explicit: public run(id) { } to public run(id: number) { } And optionally compile with noImplicitAny if you want the compiler to catch these cases for you