【发布时间】:2021-05-21 18:56:14
【问题描述】:
我正在尝试编写一个泛型类,它保留一对指向泛型类型键的特殊指针。这是这个 MVP 的 playground example
const _idKey = Symbol('_idKey')
const _sortKey = Symbol('_sortKey')
export interface BaseStoreConfig<T, Tid extends keyof T, Tsk extends keyof T | undefined> {
idKey?: Tid
sortKey?: Tsk
}
export class BaseStore<T, Tid extends keyof T & string, Tsk extends keyof T | undefined> {
public [_idKey]: keyof T | 'id'
public [_sortKey]?: keyof T | undefined
constructor({
idKey = 'id', // Errors, see below
sortKey,
}: BaseStoreConfig<T, Tid, Tsk>) {
this[_idKey] = idKey
this[_sortKey] = sortKey
}
}
这会产生一个 ts2322 错误(我已经尝试了 Tid 约束的几种变体,我总是回到这个错误)
Type 'string' is not assignable to type 'Tid'.
'string' is assignable to the constraint of type 'Tid', but 'Tid'
could be instantiated with a different subtype of constraint 'string'.ts(2322)
我通常理解这个错误,但在这种情况下我很困惑。 string 的子类型怎么不能分配给这种类型?有什么方法可以表达这个约束吗?
【问题讨论】:
-
考虑
const z: 'foo' & string = 'id';- 这不起作用,因为'id'不能分配给'foo',所以如果你用'id'以外的键传递一些T,你会遇到同样的问题.至于“有没有办法表达这种约束?” - 不是 100% 确定你在这里尝试做什么。我认为您使用 'id' 作为默认键的设计点,而不对 T 的形状做出假设会导致打字混乱。也许您可以添加一些用法示例,什么应该起作用,什么不应该等等,我可以进一步提供帮助 -
我不太明白。
Tid需要是T的键,所以T不能是'foo',否则Tid将没有可能的类型。不是使用keyof强制T成为对象吗?
标签: typescript typescript-generics