Say I have:
type User = {
...
}
I want to create a new user but set it to be an empty object:
const user: User
Here are two worthy caveats from the comments.
Either you want user to be of type
User | {}orPartial, or you need to redefine theUsertype to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. –jcalzI don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property
Usernameis left undefined, while the type annotation is saying it can't be undefined. –Ian Liu Rodrigues
One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = {};
user01.Email = "foo@bar.com";
Here is a working example for you.