Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
Need to infer second generic type from first. 'SequenceItem' could be instantiated with an arbitrary type which could be unrelated to 'T'
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
}

Playground

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

Playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!