Home > database >  typescript infer prop type from type of other property
typescript infer prop type from type of other property

Time:10-13

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)

CodePudding user response:

  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
    }
})
  • Related