microsoft / microsoft/TypeScript

FAQs: bivariance example is wrong

Aperta
#45,196 5 commenti 0 reazioni 1 assegnatario Vedi su GitHub

@RyanCavanaugh ci sta già lavorando.

Dal 5/8/2021.

Docs
Lingua principale
Go
Stelle
111k
Fork
14.4k
Merge medio
1g 19h
PR unite (30g)
117

Descrizione

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);

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Valutazione

Questa issue non è ancora stata valutata.

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.