microsoft / microsoft/TypeScript

FAQs: bivariance example is wrong

Ouverte
#45,196 5 commentaires 0 réactions 1 personne assignée Voir sur GitHub

@RyanCavanaugh y travaille déjà.

Depuis le 5/8/2021.

Docs
Langage dominant
Go
Étoiles
111k
Forks
14.4k
Merge moyen
1 j 19 h
PR mergées (30 j)
117

Description

Bug Report

the example provided here is not a clear example of bivariance:

function trainDog(d: Dog) { ... }
function cloneAnimal(source: Animal, done: (result: Animal) => void): void { ... }
let c = new Cat();

// Runtime error here occurs because we end up invoking 'trainDog' with a 'Cat'
cloneAnimal(c, trainDog);

this isn't really a problem with bivariance, and can be solved by simply using a generic on cloneAnimal:

function cloneAnimal<T extends Animal>(source: T, done: (result: T) => void) { ... }

we now correctly receive a compile error, even with all the strictness flags disabled

i would suggest using the following example instead:

class Animal {
    walk() { }
}

class Dog extends Animal {
    bark() { }
}

class Cat extends Animal {
    meow() { }
}

class List<T> {
    constructor(public values: T[]) {}
    add(value: T) {
        this.values.push(value)
    }
}

const cats: List<Cat> = new List([new Cat()])

const animals: List<Animal> = cats

animals.add(new Dog())

// runtime error, because the list of cats now has a dog in it
cats.values[1].meow()
🔎 Search Terms

faq bivariance

⏯ Playground Link

Playground link with relevant code

💻 Code
class Animal {
    walk() { }
}

class Dog extends Animal {
    bark() { }
}

class Cat extends Animal {
    meow() { }
}

declare function trainDog(d: Dog): void
declare function cloneAnimal(source: Animal, done: (result: Animal) => void): void
declare function cloneAnimalGeneric<T extends Animal>(source: T, done: (result: T) => void): void
let c = new Cat();

// Runtime error here occurs because we end up invoking 'trainDog' with a 'Cat'
cloneAnimal(c, trainDog);

// compile error: Argument of type '(d: Dog) => void' is not assignable to parameter of type '(result: Cat) => void'
cloneAnimalGeneric(c, trainDog);

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Évaluation

Cette issue n'a pas encore été évaluée.

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.