I recently came across a coding example that I found interesting:
export type TimeStamped<TContent, TContentName extends string> = {
[P in TContentName]: TContent
}
type Food = 'apple' | 'banana' | 'pear'
type TimeStampedFood = TimeStamped<Food, 'food'>
type Animal = 'cat' | 'dog' | 'horse'
type TimeStampedAnimal = TimeStamped<Animal, 'animal'>
const banana: TimeStampedFood = {food: 'banana'}
const cat: TimeStampedAnimal = {animal: 'cat'}
console.log(banana, cat)
While the above example is functional, I decided to enhance it by adding creation and expiry date tracking for these objects, as shown below:
export type TimeStamped<TContent, TContentName extends string> = {
[P in TContentName]: TContent,
createdAt: DateTimeString,
expiresAt?: DateTimeString
}
type Food = 'apple' | 'banana' | 'pear'
type TimeStampedFood = TimeStamped<Food, 'food'>
type Animal = 'cat' | 'dog' | 'horse'
type TimeStampedAnimal = TimeStamped<Animal, 'animal'>
const banana: TimeStampedFood = {
food: 'banana',
createdAt: '2020-01-01T00:00:00Z',
expiresAt: '2020-01-01T01:00:00Z'
}
const cat: TimeStampedAnimal = {
animal: 'cat',
createdAt: '2016-01-01T00:00:00Z',
expiresAt: '2023-01-01T01:00:00Z'
}
console.log(`The ${banana.food} expires at ${banana.expiresAt}`)
However, I encountered some errors while trying to define properties dynamically within the object:
Expecting newline or semicolon
Unnecessary label 'createdAt'
TS2304: Cannot find name 'expiresAt'
TS1128: Declaration or statement expected.
I'm looking for a way to have an object with createdAt
and optionally expiresAt
properties defined, while allowing flexibility in naming the content property. Do you know of a solution for this issue?