You have to add as const
to unitsOfTime
, because TS infers it as a stirng[]
and duration
is not indexed object.
Take a look on Duration
interface:
interface Duration {
clone(): Duration;
humanize(argWithSuffix?: boolean, argThresholds?: argThresholdOpts): string;
humanize(argThresholds?: argThresholdOpts): string;
abs(): Duration;
as(units: unitOfTime.Base): number;
get(units: unitOfTime.Base): number;
milliseconds(): number;
asMilliseconds(): number;
seconds(): number;
asSeconds(): number;
minutes(): number;
asMinutes(): number;
hours(): number;
asHours(): number;
days(): number;
asDays(): number;
weeks(): number;
asWeeks(): number;
months(): number;
asMonths(): number;
years(): number;
asYears(): number;
add(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration;
subtract(inp?: DurationInputArg1, unit?: DurationInputArg2): Duration;
locale(): string;
locale(locale: LocaleSpecifier): Duration;
localeData(): Locale;
toISOString(): string;
toJSON(): string;
isValid(): boolean;
/**
* @deprecated since version 2.8.0
*/
lang(locale: LocaleSpecifier): Moment;
/**
* @deprecated since version 2.8.0
*/
lang(): Locale;
/**
* @deprecated
*/
toIsoString(): string;
}
You are allowed to use only existing props as indexes.
When you add as const
, TS will allow you to use unitsOfTime
values as a Durarion
index
import * as moment from 'moment'
const duration = moment.duration(5000)
const unitsOfTime = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds'] as const
const timeBreakdown = unitsOfTime.map((unit) => duration[unit]())
`