'Infer type of object property to be passed to object function as argument

I'm trying to define a function that accepts an object with a data type and a function that gets that data type as it's argument.

const test = <
  Data extends object,
  C extends {init: Data; serialize: (d: Data) => any}
>(
  component: C
) => {}

But when I try to use it, TypeScript can only infer the object data type that the Data type extends and not the actual shape of the Data property:

test({
  init: {opa: 'super'},
  serialize: (data) => {
    // Property 'opa' does not exist on type 'object'
    return data.opa
  }
})

TypeScript Playground link

How do I define Data so that TypeScript can correctly infer it's shape?



Solution 1:[1]

C doesn't need to be a type parameter, just make it the type of component:

const test = <
    Data extends object
>(
    component: {init: Data; serialize: (d: Data) => any} // <====
) => {
};

test({
    init: {opa: 'super'},
    serialize: (data) => {
        return data.opa;
    }
});

Playground link

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 T.J. Crowder