Skip to main content

Type Inference

DynamoDB-Toolbox exposes several generic types to infer custom types from your entities.

Which one you should use depends on your usage context, for instance, whether it’s within a write or a read operation.

Writes​

For write operations, DynamoDB-Toolbox exposes the following generic types:

  • ValidItem: A valid entity item
  • InputItem: Similar to ValidItem, but with defaulted and linked attributes optional
  • TransformedItem: A valid entity item after transformation
import type {
InputItem,
ValidItem,
TransformedItem
} from 'dynamodb-toolbox/entity'

type Input = InputItem<typeof PokemonEntity>
type Valid = ValidItem<typeof PokemonEntity>
type Transformed = TransformedItem<typeof PokemonEntity>

By default, those generics use the put write mode, but you can switch to the key or update modes with the mode option. This impacts which the presence and requiredness of attributes:

type ValidKey = ValidItem<
typeof PokemonEntity,
{ mode: 'key' }
>
type ValidUpdate = ValidItem<
typeof PokemonEntity,
{ mode: 'update' }
>
Example

Here are step-by-step examples:

☝️ Entity
const PokemonEntity = new Entity({
table,
schema: schema({
// key attributes
pokemonClass: string()
.key()
.transform(prefix('POKEMON'))
.savedAs('partitionKey'),
pokemonId: string().key().savedAs('sortKey'),

// other attributes
name: string().optional(),
level: number().default(1)
}).and(prevSchema => ({
levelPlusOne: number().link<typeof prevSchema>(
({ level }) => level + 1
)
}))
// timestamps
timestamps: true
...
})
πŸ”Ž 'put' mode
{
"pokemonClass": "pikachu",
"pokemonId": "123",
"name": "Pikachu"
}
πŸ”Ž 'key' mode
{
"pokemonClass": "pikachu",
"pokemonId": "123",
}
+ (Only key attributes are required)
πŸ”Ž 'update' mode
{
"pokemonClass": "bulbasaur",
"pokemonId": "123",
"name": "PlantyDino",
}

For convenience, DynamoDB-Toolbox also exposes the following generic types:

  • KeyInputItem: Similar to InputItem in the key mode.
  • SavedItem: Similar to TransformedItem but adds the PrimaryKey of the Entity's Table
import {
KeyInputItem,
SavedItem
} from 'dynamodb-toolbox/entity'

type KeyInput = KeyInputItem<typeof PokemonEntity>
type Saved = SavedItem<typeof PokemonEntity>

Reads​

DynamoDB-Toolbox exposes the FormattedItem generic type which is similar to ValidItem, except that hidden fields are omitted:

import type { FormattedItem } from 'dynamodb-toolbox/entity'

type Formatted = FormattedItem<typeof PokemonEntity>