【发布时间】:2021-07-28 17:22:45
【问题描述】:
我有这个用例,我有一个泛型类和一个包含泛型类的多个成员的容器类。我想使用setViaFunction 来设置容器类的成员,而不取决于它们的类型。但是我收到以下错误:Argument of type 'string | boolean' is not assignable to parameter of type 'never'. Type 'string' is not assignable to type 'never'.(2345)typescript playground link
另请注意,setAnyMember 手动执行相同的操作,但并非总是可以执行不会产生该错误。
还有其他方法可以在 typescript 中实现此功能吗?
class GenericClass<T> {
public value: T
constructor(_value: T){
this.value = _value
}
setValue(_value:T){
this.value = _value
}
}
class ContainerClass {
sthString = new GenericClass('sdad')
sthBoolean = new GenericClass(true)
setAnyMember = (field: 'sthString' | 'sthBoolean', val: string | boolean) => {
this[field].value = val
}
setViaFunction = (field: 'sthString' | 'sthBoolean', val: string | boolean) => {
this[field].setValue(val)
}
}
【问题讨论】:
标签: typescript typescript-generics