Skip to content

Parameters<typeof someFunction> does not preserve type constraint or parameter inference. #54014

Closed as not planned
@DrSammyD

Description

@DrSammyD

Given the following two types.

type Channel = {
  [key: string]: number;
};

type T<C extends Channel> = {
  channel: C;
  props: (keyof C)[];
};

The following function is able to correctly constrain the type of the second parameter given the following function declaration and call.

function createObject<C extends Channel>(channel: C, props: (keyof C)[]): T<C> {
  return {
    channel,
    props,
  };
}

const someObject = createObject(
  {
    Stuff: 1,
    Yarn: 2,
  },
  ['Stuff', 'Yarn', 'Thing'] // If you try to add a string that is not a key of 'channel', you'll get a type error. Thing is inferred invalid, and I don't have to specify a generic property
);

However, this constraint is not preserved in the Parameters utility type.

let thing: Parameters<typeof createObject> = [
  {
    "Stuff": 1,
    "Yarn": 2,
  },
  ["Yarn", "Stuff", "Thing"] // So... that constraint wasn't preserved.
]

At least not until the generic is explicitly set.

let thingAgain: Parameters<typeof createObject<{"Stuff":number;"Yarn":number}>> = [
  {
    "Stuff": 1,
    "Yarn": 2,
  },
  ["Yarn", "Stuff", "Thing"] // And we're back!
]

Ultimately, the desired functionality is to have types obtain the same type inference as functions without a runtime requirement to keep the typing/code dry.

Playground link

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions