Skip to content
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

disallow bi-variant assignment compatibility for function reference parameters #5961

Closed
zpdDG4gta8XKpMCd opened this issue Dec 6, 2015 · 0 comments

Comments

@zpdDG4gta8XKpMCd
Copy link

Problem

In current TypeScript the following is permitted. Which makes point-free programming style a very risky business.

interface A { x: nuber; }
interface B { x: number, y: string }
function copyB(value: B) : B {
   return { x: value.x, y: value.y };
}
let values : A[] = [];
let copied= values.map(copyB); // <-- a problem due to using bi-variance for checking assignment compatibility

Workaround

One can use function literals instead of references, but this brings unnecessary overhead with an extra function wrap.

let copied = values.map(value => copyB(value)); // <-- gives a compile error as expected

Solution idea

During compiling (internally), why won't we transform arguments that are FUNCTON REFERENCES (problematic) into arguments that are FUNCTION LITERALS (that work as expected)?
It looks like that such transformation can be done 100% mechanically:

  • pull the signature of a function specified as a reference
  • replace the function reference with the function literal by:
    • matching each parameter of the pulled signature with a parameter of the new function literal
    • using the result of the function reference invokation as the return value of the function literal
// before transformation:
...map(copyB); // <-- function reference
// after transformation:
...map(value => copyB(value)) // <-- function literal
@zpdDG4gta8XKpMCd zpdDG4gta8XKpMCd changed the title bi-variant assignment compatibility for function parameters disallow bi-variant assignment compatibility for function parameters Dec 6, 2015
@zpdDG4gta8XKpMCd zpdDG4gta8XKpMCd changed the title disallow bi-variant assignment compatibility for function parameters disallow bi-variant assignment compatibility for function reference parameters Dec 6, 2015
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant