如何在TypeScript中设置下限类型参数? [英] How to set lower-bound to type parameters in TypeScript?
问题描述
在TypeScript(我的版本:2.1.1)中,可以设置一个上限来键入这样的参数:
In TypeScript (my version: 2.1.1), it is okay to set an upper-bound to type parameters like this:
class Animal {}
class Cat extends Animal {}
class Kitten extends Cat{}
function foo<A extends Animal>(a: A) { /* */ }
如何在A
上设置下限?以下代码不起作用:
How can I set a lower-bound on A
? The following code does not work:
class Animal {}
class Cat extends Animal {}
class Kitten extends Cat{}
function foo<A super Kitten>(a: A) { /* */ }
这将导致编译错误.
在GitHub问题中,有人建议使用TypeScript存储库中的#13337
People in the GitHub issue #13337 of the TypeScript repo have suggested to use
function foo <X extends Y, Y>(y: Y) { /* */ }
到X
的下界Y
.但是,这并不涵盖我的情况,在这种情况下,X
是实际类型而不是类型参数.
to lower-bound Y
with X
. But this does not cover my case, in which X
is an actual type instead of a type parameter.
是否有关于如何将类型参数下限的任何想法?
Any thoughts on how to lower-bound a type parameter?
推荐答案
TypeScript尚不支持泛型的下限.目前正在讨论这样的建议-TypeScript开发人员不确定是否需要这样的功能.因此,我们只能等待并希望,他们将同意实施.
Lower-bound for generics is not supported by TypeScript yet. Such suggestion is currently discussed - TypeScript developers are not sure that such feature is necessary. So, we can only wait and hope, that they will agree to implement it.
在此处查看TypeScript问题跟踪器中的问题- https://github.com/Microsoft/TypeScript/issues/14520
See the issue in TypeScript issue tracker here - https://github.com/Microsoft/TypeScript/issues/14520
这篇关于如何在TypeScript中设置下限类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!