相关疑难解决方法(0)

TypeScript:子类型和协变参数类型

常识表明,子类型在返回类型方面应该是协变的,但在参数类型方面应该是逆变的.因此,应该拒绝以下内容,因为严格协变的参数类型E.f:

interface C {
   f (o: C): void
}

interface D extends C {
   g (): void // give D an extra service
}

class E implements C {
   // implement f with a version which makes stronger assumptions
   f (o: D): void {
      o.g() // rely on the extra service promised by D
   }
}

// E doesn't provide the service required, but E.f will accept
// an E argument as long as I invoke …
Run Code Online (Sandbox Code Playgroud)

covariance subtyping typescript

7
推荐指数
1
解决办法
947
查看次数

Typescript数组接受错误的类型

我希望以下代码无法转换,因为B不应该是array.push的有效类型.我错过了什么?

class A {};
class B {};
const arr: A[] = [];
arr.push(new B());
Run Code Online (Sandbox Code Playgroud)

arrays typescript

1
推荐指数
1
解决办法
38
查看次数

标签 统计

typescript ×2

arrays ×1

covariance ×1

subtyping ×1