Reputation: 479
Let's say I have a generic type T and I want to initialize an empty object of type T. I imagine something like this but I can't get it to work.
type Phone = {
number: string;
isMain: boolean;
}
const newPhone = createEmptyObj<Phone>();
console.log(newPhone);
/*
{
number: '';
isMain: false;
}
*/
Upvotes: 0
Views: 636
Reputation: 13539
No, it's impossible. Because it's a type
you have to define everything manually, the same applies to an interface
.
If you want to have default values you need to use a class
with defined default values.
class Phone {
number: string = '';
isMain: boolean = false;
}
const newPhone = new Phone();
console.log(newPhone);
/*
{
number: '';
isMain: false;
}
*/
Upvotes: 1