Trying to create a generic class that holds a pair of special pointers to keys of a generic type. Check out an example in this playground demo.
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
}
}
A ts2322 Error is thrown (tried various constraints for Tid
, still facing the error)
Type 'string' is not assignable to type 'Tid'.
'string' can be assigned to 'Tid', but 'Tid' may have a different subtype of 'string'.ts(2322)
Although I grasp the concept of this error, it's puzzling in this scenario. How can a subtype of string
not be compatible with this type? Any suggestions on how to define this constraint?