dynamodb-toolbox icon indicating copy to clipboard operation
dynamodb-toolbox copied to clipboard

Unable to convert date string to JS Date instance

Open dmeehan1968 opened this issue 7 months ago • 0 comments

I have a field which represents an ISO 8601 timestamp (aside from created/update timestamps) which I want to be able to handle as a Date object (due to making several comparison once the entity has been read from the DB.

It seems that the entity type doesn't infer the actual type from either format or default, which could return something other than the attributes type of 'string'.

I see from the docs that you can override the action call or the Entity with the correct shape - an 'Overlay' - (which also effectively disables automatic type inference.

const SensorEntity = new Entity({
  name: 'Sensor',
  attributes: {
    devEUI: { type: 'string', partitionKey: true },
    sensorId: { type: 'number', sortKey: true },
    lastCompliance: { type: 'string', format: (v: string) => new Date(v), transform: (v: Date) => v.toISOString() },
  },
  table: MyTable
} as const)

Original code:

const { Item: sensor } = SensorEntity.get({ devEUI: 'XXX', sensorId: 0})
console.log(typeof sensor.lastCompliance)          // string

With overlay:

const { Item: sensor } = SensorEntity.get<EntityItem<SensorEntity> & { lastCompliance: Date }>({ devEUI: 'XXX', sensorId: 0})
console.log(sensor.lastCompliance instanceof Date)          // true

However, the IDE's (Jetbrains) type inference seems to show an expanded version of Date which cannot them be assigned to a Date

Type as inferred:

Screenshot 2024-07-03 at 19 16 59

Attempt to assign:

Screenshot 2024-07-03 at 19 19 35

The same happens if I try to do the same on Entity.

It also seems to mess up put calls.

It seems to be something about Date as a plain JS object seems to be interpretted correctly.

dmeehan1968 avatar Jul 03 '24 18:07 dmeehan1968