TypeScript:使用字符串/字符串和字符串/谓词映射中的字符串和谓词填充映射

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

我有

Map
string
string

我还有一个 
const strToStr = new Map<string, string>([ ['foo', 'foo'], ['bar', 'qux'], ]);

Map
到接受字符串的谓词函数:
string

第三个 
const strToFnc = new Map<string, (_: string) => boolean>([ ['baz', (_: string) => true], ['buz', (_: string) => false], ]);

应通过

Map
:
 存储 
string
 谓词函数
string

对于
const predicates = new Map<string, (_: string) => boolean>();

/

string
条目,构造并添加了谓词函数:
string

这个效果很好。但是,我无法添加其他
strToStr.forEach((k) => predicates.set(k, (_) => (k == strToStr.get(k))));

的谓词:

Map

strToFnc.forEach((k) => predicates.set(k, strToFnc.get(k)));
既然
temp.ts:11:40 - error TS2345: Argument of type '(_: string) => boolean' is not assignable to parameter of type 'string'. 11 strToFnc.forEach((k) => predicates.set(k, strToFnc.get(k))); ~ temp.ts:11:56 - error TS2345: Argument of type '(_: string) => boolean' is not assignable to parameter of type 'string'. 11 strToFnc.forEach((k) => predicates.set(k, strToFnc.get(k))); ~ Found 2 errors in the same file, starting at: temp.ts:11

返回一个谓词函数,为什么这个操作不起作用?

    

typescript dictionary predicate
1个回答
0
投票
strToFnc.get('...')

对象

forEach()
方法的行为与您想象的不同。如果你看一下
它的打字
Map

回调的第一个参数将从地图接收

,其第二个参数接收键。 看起来您不小心使用了值而不是键。假设您确实打算使用密钥,您需要类似的东西

interface Map<K, V> { forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void; }

当然你不需要 
strToStr.forEach((_, k) => predicates.set(k, (_) => (k == strToStr.get(k)))); strToFnc.forEach((_, k) => predicates.set(k, strToFnc.get(k)!));

在那里,因为你也有价值:

get()

Playground 代码链接

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