How would you type this objects in typescript ?
I have one special "datetime" key that is a Date, the rest of the keys are numbers. But I don't know in advance which keys will be set on each object. Examples values:
type Metrics = ??????
const example1: Metrics = {
datetime: new Date(),
activity: 12.34,
min: 12.34,
max: 12.34,
}
const example2: Metrics = {
datetime: new Date(),
avg: 12.34,
}
Here is what I tried:
type Metrics = {
datetime: Date,
[key: string]: number,
}
// ERROR on the type definition:
// Property 'datetime' of type 'Date' is not assignable to string index type 'number'
type Metrics = {
datetime: Date
} & {
[key: string]: number
}
// ERROR on the variable assignment:
// Type '{ datetime: Date; activity: number; min: number; max: number; }' is not assignable to type 'Metrics'.
// Type '{ datetime: Date; activity: number; min: number; max: number; }' is not assignable to type '{ [key: string]: number | null; }'.
// Property 'datetime' is incompatible with index signature.
// Type 'Date' is not assignable to type 'number'.