Skip to content

Docs: function parameter bivariance #14973

Closed
@pkch

Description

@pkch

I have found these two super useful, but rather unrelated, explanations of why function parameters are bivariant in TypeScript. Would it be helpful to merge them into one?

The first one is that the programmer may know that an object of type T[] will be only read from or only written to, but has no way of communicating that knowledge to TypeScript. Since the methods that write to an array are contravariant in T (T is their argument type) and the methods that read from the array are covariant in T (T is their return type), TypeScript permits either direction even though it cannot statically verify correctness.

The second one is that the programmer may know that the correct type of one argument (which is a function) may depend on the type of another argument; and more specifically, in a common JS pattern, it is the function argument type that varies. Again, there is no way to express it to TypeScript. Rather than giving up completely, TypeScript offers at least partial type safety by asking the programmer to indicate the broadest argument type that the function might accept, which allows it to use bivariance in its type check.

Edit: discussion in #1394 and #10717 is highly relevant.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions