简体   繁体   中英

In TypeScript, define a typed function parameters type

Let's declare a generic function:

const fun = <E = any, V = any>(params: { value: V; getValue: (e: E) => V; }) => { /**/ }

In another place, we have a consumer code, which should be typed, and now it causes TS errors:

type E = { value: string };

type Params = Parameters<typeof fun>[0];

const run = (params: Params) => {

  // expecting params.value to be a string
  // TS2339: Property 'length' does not exist on type 'unknown'.
  if (params.value.length > 0) {

    // TS2345: Argument of type '{ value: unknown; getValue: (e: unknown) => unknown; }'
    // is not assignable to parameter of type '{ value: string; getValue: (e: E) => string; }'.
    //   Types of property 'value' are incompatible.
    //      Type 'unknown' is not assignable to type 'string'.
    fun<E, string>(params);
  }
};

Is there a way to get the type of parameters of a typed function? So that Params was { value: string; getValue: (e: E) => string } { value: string; getValue: (e: E) => string } . Something like Parameters<typeof fun<E,string>>[0] .

If I understand correctly, you could make the Params type generic.

something like this:

const fun = <E = any, V = any>(params: { value: V; getValue: (e: E) => V; }) => { /**/ }

type Params<E> = Parameters<typeof fun<E,string>>[0];

const run = function<E>(params: Params<E>) {
  if (params.value.length > 0) {
    fun<E, string>(params);
  }
};

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