Skip to content

Covariance, contravariance and assignability #55603

Closed as not planned
Closed as not planned
@aswinsvijay

Description

@aswinsvijay

🔎 Search Terms

covariance
contravariance

🕗 Version & Regression Information

(Please suggest a better title 😅)

Recently Andrew Burgess posted a video related to covariance and contravariance, and also the in and out keywords

Noticed issue related to assignability while playing around with the code

  • This is the behavior in every version I tried

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.2.2&ssl=13&ssc=1&pln=15&pc=1#code/C4TwDgpgBAUg9gIygXigbwFBShAdgRwFcJiATAQWAC4oARAQ2AgG4spgAne3AZ3oGNgASzi4AkqRo9OQ3AHNW2XPQC2EKTPmsAvqwyhIUAAocRp0PCSpLUAGTo2YU3HMganYoqgAbCADcIbxoARigAHygAJnCoAGYdPQNoAEViYgAeGAA+FAdsPCISdSgACgArGhgAShQcvzghUi85CGBLGhLGjVN5GuQcmC8AeiGcAjSIcsqqmnrG4dGWtsROyShpHrkZ2ASMDFIIfm96Dmh+UWkoMsRUoppbjMss1gOjk7OL4CgnMyELG4m9wm6RMv3+CGee3OvC++FiQKKmUQOVQ1wQDxYGGhl3wABYEY9kbkfi4-iBLBi9NjYQBWAkQEHOVxPXJoylYz5QfAANnpjLB5KJqBJzIBRVYQA

💻 Code

type Job = {
  enqueuedAt: Date;
  transactionId: string;
  name: string;
};

type PriorityJob = Job & {
  priority: true;
  level: 1 | 2 | 3;
};

type Queue<J> = {
  enqueue: (j: J) => void;
  getJob: (id: string) => J;
  // enqueue(j: J): void;
  // getJob(id: string): J;
};

declare const jobQueue: Queue<Job>;
declare const priorityJobQueue: Queue<PriorityJob>;

const q3: Queue<Job> = jobQueue;
const q4: Queue<Job> = priorityJobQueue;

const q5: Queue<PriorityJob> = jobQueue;
const q6: Queue<PriorityJob> = priorityJobQueue;

🙁 Actual behavior

If the methods defined in the Queue type (without using in and out keywords) used the arrow function syntax, there are two of the four assignments which are errors.
But if using the normal function syntax, only one is erroring.

🙂 Expected behavior

Consistent behaviour is expected in all cases.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions