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
Compiler allows narrower method signature than implemented interface #58315
Comments
This is working as intended and mentioned in the FAQ: https://github.com/microsoft/TypeScript/wiki/FAQ#parameter-arity-variance-is-correct |
Thank you @MartinJohns for your quick reply. |
That's not quite the right part of that document, see https://github.com/microsoft/TypeScript/wiki/FAQ#:~:text=A%20method%20and%20a%20function%20property%20of%20the%20same%20type%20behave%20differently. |
Rare MartinJohns L π Anyway I just updated the FAQ with a new entry about method bivariance; see https://github.com/microsoft/TypeScript/wiki/FAQ#why-method-bivariance |
βΉοΈ @CComparon it works as you expect if you use the property syntax for class methods class B {
f = (a: number) => {}
}
class C { // same result when using an interface
f = (a: number | string) => {}
}
async function main(): Promise<void> {
const b: C = new B(); // Error: Type 'B' is not assignable to type 'C'... Type 'string' is not assignable to type 'number'.
console.log(b.f(5));
console.log(b.f("5"));
} |
@RyanCavanaugh The new FAQ is missing a TOC, that threw me off and made finding things a lot harder. |
Thanks both for pointing me to the rationale behind this language tradeoff. |
π Search Terms
interface implements allows narrower argument type
π Version & Regression Information
This is the behavior in every version I tried (4.7.x and 5.4.x)
β― Playground Link
https://www.typescriptlang.org/play/?noUnusedLocals=true&noUnusedParameters=true&target=8&jsx=0&useUnknownInCatchVariables=true&noImplicitOverride=true&noFallthroughCasesInSwitch=true&suppressImplicitAnyIndexErrors=false&exactOptionalPropertyTypes=true&ts=5.4.5#code/JYOwLgpgTgZghgYwgAgJLIN4ChnJgCjgC5kQBXAWwCNpkAfZAZzClAHMBKE866AbiwBfLFgQAbOI0bIAwsmAUADmIgUI4aemy4CxUpRpQu+3lEw5cyKBDBkoIZHGQAqZACYBuYcNEB7EMzICCToALykEADusvgcAgj+jL4qAHRivmz4CCkEAKwcADRBOfgARAAsbqUcccgA9HXIvr6KjFhAA
π» Code
π Actual behavior
Compiler accepts code
π Expected behavior
Compiler should reject code with an error stating that the implementation method signature is not assignable to the interface method signature.
Additional information about the issue
No response
The text was updated successfully, but these errors were encountered: