我有
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
返回一个谓词函数,为什么这个操作不起作用?
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 代码链接