【发布时间】:2020-10-21 15:14:13
【问题描述】:
我想做的最少的代码复制:
const handlers = {
foo: (s: string) => s.length,
bar: (n: number) => n.toFixed(2)
}
type DataMap = {
[P in keyof typeof handlers]: {
type: P,
data: Parameters<typeof handlers[P]>[0]
}
}
type Block = DataMap[keyof DataMap];
const data: Array<Block> = []
data.forEach(block => {
if (block.type in handlers) {
// Error: Argument of type 'string | number' is not assignable to parameter of type 'never'.
handlers[block.type](block.data)
}
})
现在 forEach Error: Argument of type 'string | number' is not assignable to parameter of type 'never'. 里面有一个错误
我应该如何为这种情况编写 typeguard?
编辑:
如果现在除了断言之外没有其他解决方案,那么也许有更好的方法来构建此类数据?
【问题讨论】:
标签: typescript