我具有以下功能
function pickAndTrim <T> (keys : Array<string>, object : T ) : T {
function trim <A> (input : A) : A {
if (typeof input === "string") {
return input.trim();
}
return input;
}
let updates = R.pick(keys, object);
updates = R.map(trim, updates);
return updates;
}
注意: R是Ramda
它的作用是获取一个对象,从中选择某些键(和值),然后修剪生成的对象(如果是字符串)中的任何值。
我当前遇到的错误是:
Type 'string' is not assignable to type 'A'.
'A' could be instantiated with an arbitrary type which could be unrelated to 'string'.
我如何使打字稿肯定是字符串(因为我用typeof
对其进行了检查)
答案 0 :(得分:1)
TypeScript不会抱怨“ input”不是字符串-“'string'不可分配给类型'A'”-我认为问题是,在某些情况下TypeScript会推断函数类型f: A -> string
然后您有一些let var: A = f(x)
,但无法将字符串分配给A。
我不熟悉Rambda,但是您可以尝试使用带有类型保护的过滤器:
filter updates (x => typeof x === 'string')
所以您有一个字符串列表,然后在其上进行映射。
或者显然Ramda具有pickBy
函数:
R.pickBy((val, key) => (keys.indexOf(key) >= 0) && (typeof val === 'string'), object);
我对该库不熟悉,而且我似乎无法获得这些函数的类型信息,因此它返回“ any”,这不是很好。