【发布时间】:2021-05-30 16:55:01
【问题描述】:
我想在给定数组函数名称的情况下动态运行函数,但 TS 对 duration[unit] 提出了投诉,并显示以下消息:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Duration'.
No index signature with a parameter of type 'string' was found on type 'Duration'.ts(7053)
const duration: Duration = moment.duration(5000)
const unitsOfTime = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds']
const timeBreakdown = unitsOfTime.map((unit) => duration[unit]())
【问题讨论】:
-
并非如此。如果我按照上面答案中提供的建议仍然不起作用,我的代码将是
duration[unit as keyof Duration]()。
标签: typescript momentjs