如何在Typescript中设置泛型类的泛型参数约束?
假设我有这样的接口:如何在Typescript中设置泛型类的泛型参数约束?,typescript,generics,Typescript,Generics,假设我有这样的接口: interface Identity<TValue> { readonly value: TValue; } 但它们都不起作用。如何设置此类约束?您可能需要使用两个类型参数,如中所示: class IdentityStorage<TValue, TIdentity extends Identity<TValue>> {} class IdentityStorage{} 这表示所需的确切约束。如果你愿意放松一些约束,你可以做如下
interface Identity<TValue> {
readonly value: TValue;
}
但它们都不起作用。如何设置此类约束?您可能需要使用两个类型参数,如中所示:
class IdentityStorage<TValue, TIdentity extends Identity<TValue>> {}
class IdentityStorage{}
这表示所需的确切约束。如果你愿意放松一些约束,你可以做如下的事情
class IdentityStorage<TIdentity extends Identity<any>> {}
class IdentityStorage{}
这也会起作用,但可能会允许一些您不想要的东西(取决于Identity
中有多少属性取决于TValue
以及以何种方式…如上所述,只有一个类型为TValue
的属性,所以这很好。)
希望有帮助。祝你好运 您可能需要使用两个类型参数,如中所示:
class IdentityStorage<TValue, TIdentity extends Identity<TValue>> {}
class IdentityStorage{}
这表示所需的确切约束。如果你愿意放松一些约束,你可以做如下的事情
class IdentityStorage<TIdentity extends Identity<any>> {}
class IdentityStorage{}
这也会起作用,但可能会允许一些您不想要的东西(取决于Identity
中有多少属性取决于TValue
以及以何种方式…如上所述,只有一个类型为TValue
的属性,所以这很好。)
希望有帮助。祝你好运 你能想出一个例子,第一个版本阻止了第二个版本允许的事情吗?由于
t值
没有约束,因此它可以是任何
,但是,即使它有一个约束,并且两个类中都存在相同的约束,您是否可以对第二个版本执行第二个版本会被第二个版本阻止的操作?我认为,如果Identity
在T
中是不变的,那么两个参数都具有将是有用的。例如,假设它有一个类型为T
的getter和setter。any
版本将允许getter和setter具有不同的类型(您无法使用unknown
修复它,因为这会使setter尽可能窄)。非常感谢。正是我需要的!你能想出一个例子,第一个版本阻止了第二个版本允许的事情吗?由于t值
没有约束,因此它可以是任何
,但是,即使它有一个约束,并且两个类中都存在相同的约束,您是否可以对第二个版本执行第二个版本会被第二个版本阻止的操作?我认为,如果Identity
在T
中是不变的,那么两个参数都具有将是有用的。例如,假设它有一个类型为T
的getter和setter。any
版本将允许getter和setter具有不同的类型(您无法使用unknown
修复它,因为这会使setter尽可能窄)。非常感谢。正是我需要的!