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

147
Views
typescript infer prop type from type of other property
interface featureType<Props=any, State=any> {
  initialState: State;
  props: Props;
  processState: (props: Props, state: State) => any;
}

const feature1Comp: featureType = {
  initialState: { lastName: '' },
  props: { firstName: 'eliav' },
  processState: (props, state) => {
    props; // type should be {firstName: string} but instead is any
  },
};

why props type is not being inferred? what am I missing?

quick playground here(the URL is being cut so copy-paste the code)

(I post this question only because it takes too much time to find a solution for that issue and this is quite a common usage for typescript)

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

0

  1. Capitalize your types and interfaces (FeatureType) - that's a convention
  2. If you use generics, you should provide them to your type definiton:

const feature1Comp = FeatureType<{ firstName: string}, any>

Treat generics as a kind of 'type functions'. If you don't provide the concrete types, defaults will be used, so TS assumes Props and State are typed as any.

Update: here is what will work with infering

interface Component<P,S> {
    initialState: S,
    props: P,
    processState: (props: P, state: S) => any
}

function createComponent<P, S>(arg: Component<P, S>): Component<P, S> {
    return arg;
}

const x = createComponent({
    initialState: 'someValue',
    props: { firstName: 'Elias' },
    processState: (p, s) => {
        console.log(p.firstName) // Works
        console.log(p.lastName) // Error
    }
})
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!