generic和ramda库的curry()一起使用时,generic不适用

问题描述 投票:0回答:1

这是一个在map中通过key查找并返回一个值的函数,如果没有找到则返回一个defaultValue

import { Map } from "immutable";
import { curry } from "ramda";

export const nullishGet = curry(
  <V>(defaultValue: V, key: string, map: Map<string, V>): V =>
    map.get(key) ?? defaultValue
);

我添加了一个函数,当我要查找的值是一个数组时,将 defaultValue 设置为

[]

export const nullishGetArray = nullishGet<unknown[]>([]);

我期待的类型:

Curry<(key: string, map: Map<string, unknown[]>) => unknown[]>

但它是

Curry<(defaultValue: unknown, key: string, map: Map<string, unknown>) => unknown>

我还写了一个没有指定泛型类型的版本。像这样

export const nullishGetArray = nullishGet([])
//the type of nullishGetArray is Curry<(key: string, map: Map<string, unknown>) => unknown>

简单地说,当尝试将它与 curry 一起使用时,似乎泛型没有正确应用。

这是因为 Ramda 对 TypeScript 不友好,还是我做错了什么?

Edit objective-zeh-6ye5og

库版本
  • 拉姆达:0.28.0
  • @types/ramda: 0.28.23
javascript typescript ramda.js currying
1个回答
0
投票

有点尴尬,但你可以通过移动一些东西来实现你想要做的事情:

import Immutable from "immutable";
import * as R from "ramda";

// Define implementation outside of Ramda's curry
function nullishGetBase<V>(
  defaultValue: V,
  key: string,
  map: Immutable.Map<string, V>
): V {
  return map.get(key) ?? defaultValue;
}

// Note the explicit type here
const nullishGetArray = R.curry(nullishGetBase<unknown[]>)([]);

// result type is unknown[]
const result = nullishGetArray("foo", Immutable.Map({ foo: ["bar"] }));

我认为你的版本失败了,因为通用参数

V
没有任何约束,它将默认/回退到
unknown
。反过来,这将覆盖你扔给它的任何其他类型。

© www.soinside.com 2019 - 2024. All rights reserved.