Surprisingly, the following code does not throw a compile time error as expected.
interface Service {
}
abstract class TestService implements Service {
}
class TestServiceImpl extends TestService {
}
class Blah {
}
function getService<T extends Service>(service: T): string {
return 'hello';
}
let m = getService( Blah );
The compiler allows a type that doesn't extend Service to be passed into getService, even though the T extends Service constraint should prevent this. Any thoughts on why?
EDIT
I tried giving getService a proper body that references its parameter but it didn't change anything.
Adding something to the Service interface did make a difference, which is different from my experience with other languages.
Now there's an error in the following code, just not the one I was expecting:
interface Service {
doSomething(): number;
}
abstract class TestService implements Service {
public doSomething(): number {
return 1;
}
}
class TestServiceImpl extends TestService {
public doSomethingElse(): void {
//
}
}
function getService<T extends Service>(service: T): string {
return (<any>service).name;
}
let m = getService( TestService );
Now I get the error:
error TS2345: Argument of type 'typeof TestService' is not assignable to parameter of type 'Service'. Property 'doSomething' is missing in type 'typeof TestService'. let m = getService( TestService );
But isn't TestService supposed to implement Service?
Feeling a bit perplexed here