Create a TS function to deep call .toString() on all Date objects without type casting?

Hi, I was working on a function which should transform any instance of a specific object (for demo lets use the Date object) to a string. I wanted its signature to be like <T>(input: T) => Stringified<T> where Stringified<T> is the exact same type except the Date instaces are now string.
const withDate = {
name: 'somelist'
items: [
{id: '1', createdAt: new Date()},
{id: '2', createdAt: new Date()}
],
createdAt: new Date()
}
const withDate = {
name: 'somelist'
items: [
{id: '1', createdAt: new Date()},
{id: '2', createdAt: new Date()}
],
createdAt: new Date()
}
this would become:
const withStringDate = {
name: 'somelist'
items: [
{id: '1', createdAt: '1.1.2025'},
{id: '2', createdAt: '1.1.2025'}
],
createdAt: '1.1.2025'
}
const withStringDate = {
name: 'somelist'
items: [
{id: '1', createdAt: '1.1.2025'},
{id: '2', createdAt: '1.1.2025'}
],
createdAt: '1.1.2025'
}
I tried to do this, but all attempts i did, I had to use type casting with a seperate TS type to make sure it gave me the correct type. Is it possible to do this wihout casting and without using the any type?
1 Reply
BouncerU
BouncerU5d ago
@flowmotion You can do. You need to define a utility type that recursively replaces Date instances with string, and then create a function that applies this transformation.

Did you find this page helpful?