【问题标题】:Typing Variable as Function of Generic Type将变量键入为泛型类型的函数
【发布时间】:2020-03-31 04:00:25
【问题描述】:

我有一个通用函数类型:

type TestType<T extends HTMLElement> = (input: T) => React.Ref<T>;

我有一个变量,我想用那个类型输入它,这样我就可以为返回类型提供强大的类型保证:

const Test = (input) => {
  return React.useRef(input);
}

我无法确定将此类型应用于此变量 (Test)

我尝试过的事情:

  1. 尽可能明确:
export const Test: TestType<T extends HTMLElement> = <K extends HTMLElement>(input: K) => {
  return React.useRef<K>(input);
}
  • 编译失败,除其他错误消息外,"Cannot find name 'T'."

    1. 试图让类型推断帮助我
export const Test: TestType = (input: K) => {
  return React.useRef(input);
}
  • 不出所料,这会失败,因为 TestType 需要类型参数

当我查看 TS 文档时,我能找到的最接近的是这个 sn-p:

interface GenericIdentityFn {
    <T>(arg: T): T;
}

function identity<T>(arg: T): T {
    return arg;
}

let myIdentity: GenericIdentityFn = identity

但是我找不到任何将类型信息传递给变量声明并让 TS 推断函数参数的类型 (input) 或返回类型的方法(尽管在这种情况下,TS 很容易推断它来自实现)。

这样的事情可能吗?

【问题讨论】:

  • 这是您要找的吗? interface TestType { &lt;T extends HTMLElement&gt;(input: T): React.Ref&lt;T&gt; } 然后const Test: TestType = &lt;K&gt;(input: K) =&gt; React.useRef&lt;K&gt;(input);
  • 我觉得你不需要类型声明中的 。一个简单的类型TestType = (input: HTMLElement) =&gt; React.Ref&lt;HTMLElement&gt;;。既然你知道 T extends HTMLElement 你实际上并不需要它,typescript 将接受任何 HTMLElement 实例或从它继承的类。
  • @AlekseyL。 - 是的!随意张贴作为答案。最后可能是微不足道的,但我自己无法将它拼凑起来

标签: typescript


【解决方案1】:

所以你的方向是正确的。先用call signature定义接口:

interface TestType {
    <T extends HTMLElement>(input: T): React.Ref<T>
}

现在你可以用它来输入变量了:

const Test: TestType = <K>(input: K) => React.useRef<K>(input);

Playground


不确定用例是什么,但您也可以显式指定返回类型而不定义整个函数的类型:

const Test = <T extends HTMLElement>(input: T): React.Ref<T> => React.useRef<T>(input);

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 2019-03-05
    • 2016-09-06
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多