Diogo Mafra
Diogo Mafra

Reputation: 479

TypeScript: Is it possible to create an empty object from generic type?

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

Answers (1)

satanTime
satanTime

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

Related Questions