繁体   English   中英

在 TypeScript 中,定义类型化函数参数类型

[英]In TypeScript, define a typed function parameters type

让我们声明一个通用函数:

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

在另外一个地方,我们有一个消费者代码,应该是打出来的,现在却导致了TS错误:

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

有没有办法获取类型化函数的参数类型? 所以Params{ value: string; getValue: (e: E) => string } { value: string; getValue: (e: E) => string } Parameters<typeof fun<E,string>>[0]这样的东西。

如果我理解正确,您可以使Params类型通用。

是这样的:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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