microsoft / microsoft/TypeScript

FAQs: bivariance example is wrong

オープン
#45,196 コメント 5 件 リアクション 0 件 担当者 1 名 GitHub で見る

@RyanCavanaugh がすでに取り組んでいます。

2021年8月5日 から。

Docs
主要言語
Go
スター
111k
フォーク
14.4k
平均マージ
1日 19時間
マージ済み PR(30日)
117

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。