Home > Blockchain >  Why does this generic function produce an error?
Why does this generic function produce an error?

Time:01-02

Apologize for the vague title, but I wasn't sure how to be more specific.

Here's my code:

export type Children = Record<string, Module<any>>;

export interface Module<
  CHILDREN extends Children,
> {
  children: CHILDREN;
}

function createModule<MODULE extends Module<any>>(
  children: MODULE['children']
): MODULE {
  return {
    children
  };
}

The return statement produces the error: "Type '{ children: MODULE["children"]; }' is not assignable to type 'MODULE'."

Why does this happen? If I'm typing the children argument to be exactly the type of the children property in a Module, how is it possible that the types don't match?

CodePudding user response:

TypeScript doesn't allow this, because the type parameter might not be Module<any>. It could be a type with additional properties.

createModule<{ children: number[], extra: "oops" }>([1, 2, 3])
// supposedly returns: {
//    children: number[];
//    extra: "oops";
//}

The signature you probably want is the following, which compiles without errors:

function createModule<T extends Children>(
  children: T
): Module<T> {
  return {
    children
  };
}
  • Related