-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Implementing interfaces but being more specific - bug or feature of typescript ? #16735
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This is intentional - function return types should be compared in a covariant manner. Returning a specific type when a more general one is expected is acceptable. |
@DanielRosenwasser Thanks... And is it also ok to change an argument type to be more specific when a general one is expected as the example does ? (FormControl is a subclass of AbstractControl) |
I might be wrong, but it works of "assignability" in the sense that the one type could be assigned to the other, so TypeScript does not raise an exception. Functions in TypeScript often narrow their arguments to only operate on what they are going to operate on, making the code in the function less prone to augmenting things that it shouldn't be aware of. Putting "blinders" on your code horse is an effective pattern in TypeScript and still meets the contract. Functions are also allowed to ignore arguments that are in an interface. interface SomeFunction {
(a: string, b: string): void;
}
const foo: SomeFunction = (a) => {
console.log(a);
}
foo('foo', 'bar'); |
Does anyone know any references to dokumentation that specifies exactly how matches between interfaces and implementations should work in detail as discussed here? |
Type Compatibility discusses how TypeScript deals with assignability and soundness. |
@kitsonk Thanks for the very useful link. In particular, I think this quote from your link explains things well:
|
See also: #14973 |
TypeScript Version: 2.3.4
Unlike java/C#, typescript allows me to implement a function in an interface without having an exact match in the signature. Specificly, I can change the type of function arguments and return types as shown in the example below where I have chosen to be more specific than the interface I am implementing. I think there are benefits of doing so and the example compiles but I am unsure if it is a bug or feature of typescript (I don't want to do things that work by accident but is likely to be caught in a later version of typescript).
Code
With
Expected behavior:
Not sure - should it compile ok as it does now ?
Actual behavior:
Compiles ok.
The text was updated successfully, but these errors were encountered: