With TypeScript, how can I apply a class that implements the correct function?

The following bit of TypeScript compiles without error:

interface IPerson {
    name: string;
}
interface IVehicle {
    model?: string;
}
interface IClass {
    doSomething(person:IPerson): string;
}

class MyClass implements IClass {
    doSomething(car:IVehicle):string {
        return car.model;
    }
}

      

but I want it to throw an error because it MyClass.doSomething

accepts IVehicle

, but must accept instead IPerson

. How do I force the compiler to ensure that a class method takes the correct argument types?

+3


source to share


2 answers


This is a known issue: https://github.com/Microsoft/TypeScript/issues/7485 as mentioned in the comments by niba.



0


source


I wish I could tell you why this is happening, because it seems strange that you are not getting an error that looks like this:

index.ts(11,14): error TS2420: Class 'MyClass' incorrectly implements interface 'IClass'.
  Types of property 'doSomething' are incompatible.
    Type '(car: IVehicle) => string' is not assignable to type '(person: IPerson) => string'.
      Types of parameters 'car' and 'person' are incompatible.
        Type 'IPerson' is not assignable to type 'IVehicle'.
          Property 'model' is missing in type 'IPerson'.

      

You will get the error inserted above if you include:

interface IVehicle {
    model?: string;
}

      



in

interface IVehicle {
    model: string;
}

      

But I'm with you, I would also expect this error, regardless of the optional property in IVehicle

. Hopefully someone more familiar with the internals of the compiler can tell us why.

+1


source







All Articles