I have an interface like this (but with over 20 fields)
export interface HouseDetails {
title: string | undefined;
url: URL;
address?: string;
logo?: URL;
price?: number;
sq_meters?: number;
}
And I want to generate a record with the keys of HouseDetails
but all of its values set to a default value (for example, the empty string ""
). This is the code I tried, but when I print it to a console, it is an empty object:
function generateDefaultMapping<T extends Object, D>(default_value: D): Record<keyof T, D> {
return Object.fromEntries(Object.keys({} as T).map((key) => [key, default_value])) as Record<keyof T, D>;
}
// Use the function to create a default mapping for HouseDetails
const default_mapping<Record<keyof HouseDetails, string> = generateDefaultMapping<HouseDetails, string>("");
console.log(default_mapping) // {}
I think the problem is that this does not work like C++ templates, but, is there any way of doing it?