Type Inference
DynamoDB-Toolbox exposes several generic types to infer custom types from your schemas.
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:
ValidValue
: A valid schema valueInputValue
: Similar toValidValue
, but with defaulted and linked attributes optionalTransformedValue
: A valid schema value after transformation
import type {
InputValue,
ValidValue,
TransformedValue
} from 'dynamodb-toolbox/schema'
type Input = InputValue<typeof pokemonSchema>
type Valid = ValidValue<typeof pokemonSchema>
type Transformed = TransformedValue<typeof pokemonSchema>
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 = ValidValue<
typeof pokemonSchema,
{ mode: 'key' }
>
type ValidUpdate = ValidValue<
typeof pokemonSchema,
{ mode: 'update' }
>
Example
Here are step-by-step examples:
βοΈ Schema
const now = () => new Date().toISOString()
const pokemonSchema = item({
// key attributes
pokemonClass: string()
.key()
.transform(prefix('POKEMON'))
.savedAs('partitionKey'),
pokemonId: string().key().savedAs('sortKey'),
// timestamps
created: string().default(now),
updated: string()
.required('always')
.putDefault(now)
.updateDefault(now),
// other attributes
name: string().optional(),
level: number().default(1)
}).and(prevSchema => ({
levelPlusOne: number().link<typeof prevSchema>(
({ level }) => level + 1
)
}))