Skip to content

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

Closed
@zpdDG4gta8XKpMCd

Description

@zpdDG4gta8XKpMCd

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions