const SORT_VALUES = {
a: -1,
b: 1,
} as const
type sortWrapperReturn = -1 | 1 | 0
export const sortWrapper = <T extends string, SequenceItem = T>({
a,
b,
sequence,
}: {
a: T
b: T
sequence?: SequenceItem[]
}): sortWrapperReturn => {
if (a === b) return 0
if (sequence) {
const aIndex = sequence.indexOf(a)
const bIndex = sequence.indexOf(b)
if (aIndex === -1) return SORT_VALUES.b
if (bIndex === -1) return SORT_VALUES.a
if (aIndex > bIndex) return SORT_VALUES.b
if (aIndex < bIndex) return SORT_VALUES.a
}
return 0
}
I need to inherit the second generic type from the first so that the type from 'a' and 'b' parameters was inferred to 'sequence' parameter
a and b should be assignable to SequenceItem.
SequenceItem = T does not mean that T is assignable to SequenceItem. In order to fix it, you need to assure TypeScript that sequence argument is a set of T. Consider this example:
const SORT_VALUES = {
a: -1,
b: 1,
} as const
type sortWrapperReturn = -1 | 1 | 0
export const sortWrapper = <T extends string>({
a,
b,
sequence,
}: {
a: T
b: T
sequence?: T[]
}): sortWrapperReturn => {
if (a === b) return 0
if (sequence) {
const aIndex = sequence.indexOf(a)
const bIndex = sequence.indexOf(b)
if (aIndex === -1) return SORT_VALUES.b
if (bIndex === -1) return SORT_VALUES.a
if (aIndex > bIndex) return SORT_VALUES.b
if (aIndex < bIndex) return SORT_VALUES.a
}
return 0
}
Or, you can use intersection with T[]:
export const sortWrapper = <T extends string, Sequence = T>({
a,
b,
sequence,
}: {
a: T
b: T
sequence?: Sequence[] & T[] // < ---- change
}): sortWrapperReturn => {
// ... code
}
sortWrapper({ a: 'a', b: 'b', sequence: ['a', 'b', 'c'] }) // ok