【问题标题】:Infer generic for constant?推断常量的泛型?
【发布时间】:2021-10-02 02:27:01
【问题描述】:

是否可以在 Typescript 中为常量推断泛型类型?

具体来说,我经常发现自己编写标识函数只是为了对 typescript 中的值强制执行泛型类型约束:

function inferGeneric<T>(t: MyTypeWithGeneric<T>) {
  return t;
}

const foo = inferGeneric(value);

例如:Typescript: force key and value to be of the same type?

没有这个功能可以做到吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    据我所知,目前没有此语法。您可以手动指定类型,但可以更详细。

    使用另一个问题中的示例:

    type KeyValueSameDict<Keys extends string> = {
      [v in Keys]?: v;
    };
    
    function inferGeneric<T extends string>(t: KeyValueSameDict<T>) {
      return t;
    }
    
    const x = inferGeneric({ foo: 'foo', bar: 'bar' } as const);
    const y = { foo: 'foo', bar: 'bar' } as KeyValueSameDict<string>; // Loose
    const z = { foo: 'foo', bar: 'bar' } as KeyValueSameDict<"foo" | "bar">; // Same as x
    
    // Something like this is probably what one would want here, but this is invalid:
    const error = { foo: 'foo', bar: 'bar' } as KeyValueSameDict<infer T>;
    

    【讨论】:

      【解决方案2】:

      我不确定您为什么需要强制使用泛型类型,因为以前的类型应该与您可能想要泛型类型的任何东西兼容。

      唉,你想要的目前是不可能的,但是 TypeScript 存储库中有一个开放的 issue 和一个 PR 用于这种类型参数推断。我不完全确定它涵盖了您的用例,但它应该是一个很好的起点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-07-23
        • 2018-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多