TypeScript 中的字典类型不接受方法哈希
Dictionary type in TypeScript not accepting a hash of methods
我从 lowdb via @types/lowdb 导入类型,当使用他们的 mixins()
方法在商店上配置 mixins 时,它抱怨我传递的参数不匹配类型:
Argument of type 'Map<string, Function>' is not assignable to parameter of type 'Dictionary<(...args: any[]) => any>'.
Index signature is missing in type 'Map<string, Function>'.ts(2345)
我假设 mixins
方法接受的类型本质上是一个用字符串索引的函数映射。所以认为 Map<string, function>
通过它是可以接受的事情。上下文:
async setupStore ({storeName, storeMixins} : {storeName: string, storeMixins: Map<string, Function>}) {
const store: LowdbSync<any> = await lowdb(new StoreMemoryAdapter(storeName))
store._.mixin(storeMixins)
}
我想我在这里的困惑是缺乏对 Dictionary<(...args: any[]) => any>
实际期望的理解。我自己无法使用类型声明,因为它在用户空间中不可用。但也许 Map<string, Function>
不是正确的等价物?
这里的错误信息最重要:
Index signature is missing in type 'Map<string, Function>'.ts(2345)
您可以找到有关索引签名的更多信息in the docs
让我们看一下Map
类型定义:
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
readonly size: number;
}
您可能已经注意到没有索引签名 {[prop: string]:any}
这意味着不可能像这样做smtg:Map<string, string>[string]
。
考虑这个例子:
type Fn = (...args: any[]) => any
type A = Map<string, Fn>[string] // error
type B = Record<string, Fn>[string] // ok -> Fn
interface C {
[prop: string]: Fn
}
type Cc = C[string] // ok -> Fn
顺便说一句,在索引上下文中,类型和接口之间存在细微差别。
请参阅 答案。
我从 lowdb via @types/lowdb 导入类型,当使用他们的 mixins()
方法在商店上配置 mixins 时,它抱怨我传递的参数不匹配类型:
Argument of type 'Map<string, Function>' is not assignable to parameter of type 'Dictionary<(...args: any[]) => any>'. Index signature is missing in type 'Map<string, Function>'.ts(2345)
我假设 mixins
方法接受的类型本质上是一个用字符串索引的函数映射。所以认为 Map<string, function>
通过它是可以接受的事情。上下文:
async setupStore ({storeName, storeMixins} : {storeName: string, storeMixins: Map<string, Function>}) {
const store: LowdbSync<any> = await lowdb(new StoreMemoryAdapter(storeName))
store._.mixin(storeMixins)
}
我想我在这里的困惑是缺乏对 Dictionary<(...args: any[]) => any>
实际期望的理解。我自己无法使用类型声明,因为它在用户空间中不可用。但也许 Map<string, Function>
不是正确的等价物?
这里的错误信息最重要:
Index signature is missing in type 'Map<string, Function>'.ts(2345)
您可以找到有关索引签名的更多信息in the docs
让我们看一下Map
类型定义:
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
set(key: K, value: V): this;
readonly size: number;
}
您可能已经注意到没有索引签名 {[prop: string]:any}
这意味着不可能像这样做smtg:Map<string, string>[string]
。
考虑这个例子:
type Fn = (...args: any[]) => any
type A = Map<string, Fn>[string] // error
type B = Record<string, Fn>[string] // ok -> Fn
interface C {
[prop: string]: Fn
}
type Cc = C[string] // ok -> Fn
顺便说一句,在索引上下文中,类型和接口之间存在细微差别。
请参阅