【发布时间】:2020-01-25 23:46:58
【问题描述】:
这是一个非常常见的 JavaScript 模式:
function mapThruWrapper(module) {
const replacement = {}
Object.getOwnPropertyNames(module).forEach(function(key) {
const val = module[key]
if (val instanceof Function) {
replacement[key] = wrapperFunc.bind(null, val)
} else {
replacement[key] = val
}
})
return replacement
}
我正在尝试在 TypeScript 中强输入此内容,并且我已经达到了以下内容:
function mapThruWrapper<M extends { [X: string]: unknown }>(module: M): M {
const replacement: M = {}
Object.getOwnPropertyNames(module).forEach(function(key) {
const val = module[key]
if (val instanceof Function) {
replacement[key] = wrapperFunc.bind(null, val)
} else {
replacement[key] = val
}
})
return replacement
}
不幸的是,这仍然是producing errors 之类的:
src/excmd.ts:186:10 - error TS2322: Type '{}' is not assignable to type 'M'.
'{}' is assignable to the constraint of type 'M', but 'M' could be instantiated with a different subtype of constraint '{ [X: string]: unknown; }'.
186 const replacement: M = {}
~~~~~~~~~~~
src/excmd.ts:192:10 - error TS2536: Type 'string' cannot be used to index type 'M'.
192 replacement[key] = buckleScriptErrorTrampoline.bind(null, $val)
~~~~~~~~~~~~~~~~
如何对这样的对象的成员进行强类型泛型迭代和包装?
【问题讨论】:
标签: typescript types typescript-generics parametric-polymorphism type-variables