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​

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

  • ReadItem: A valid entity item (differs from ValidItem as options are different, see below)
  • FormattedItem: Similar to ReadItem, but with hidden attributes omitted
import type {
ReadItem,
FormattedItem
} from 'dynamodb-toolbox/schema'

type Read = ReadItem<typeof PokemonEntity>
type Formatted = FormattedItem<typeof PokemonEntity>

By default, those generics return complete items, but you can filter attributes and/or apply Partial (deeply) with the attributes and partial options:

type Filtered = FormattedItem<
typeof PokemonEntity,
{ attributes: 'level' | 'name' | 'deep.attr[0].path' }
>
type Partial = FormattedItem<
typeof PokemonEntity,
{ partial: true }
>