简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM