I want to have a Typescript type that changes (recursively) the type of a property depending on the properties name.
The use case is to have a proper typed function that converts strings ending with '_at', in an object, to Dates.
How would I enable this? Is it even possible? Code snippet in Typescript Playground
const isDate = (obj: unknown) => Object.prototype.toString.call(obj) === '[object Date]';
const isObject = (obj: unknown) => ((typeof obj === 'function' || (typeof obj === 'object' && !!obj)) && Array.isArray(obj) === false && !isDate(obj));
// What should be the return type of this function?
const dateStringsToDate = (dbResult: any) => {
for (const key of Object.keys(dbResult)) {
// we assume every timestamp ends like this e.g. created_at, begin_at
if (key.endsWith('_at') && typeof dbResult[key] === 'string') {
dbResult[key] = new Date(dbResult[key]);
}
if (isObject(dbResult[key])) dbResult[key] = dateStringsToDate(dbResult[key]);
if (Array.isArray(dbResult[key]))
dbResult[key] = dbResult[key].map((x: any) => dateStringsToDate(x));
}
return dbResult;
};
// example usage
const post = { created_at: '2022-01-15T14:31:05.252Z', title: 'foo'}
const convertedPost = dateStringsToDate(post)
console.log(convertedPost) // { created_at: Sat Jan 15 2022 14:31:05 GMT+0100 (Central European Standard Time), title: 'foo' }
// how to get the proper type for convertedPost?