patterntypescriptCritical
TypeScript empty object for a typed variable
Viewed 0 times
typescriptemptyobjectfortypedvariable
Problem
Say I have:
I want to create a new
How do I do this? I don't want the variable to be
type User = {
...
}I want to create a new
user but set it to be an empty object:const user: User = {}; // This fails saying property XX is missing
const user: User = {} as any; // This works but I don't want to use anyHow do I do this? I don't want the variable to be
null.Solution
Caveats
Here are two worthy caveats from the comments.
Either you want user to be of type
I 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
Answer
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.
Here is a working example for you.
Here are two worthy caveats from the comments.
Either you want user to be of type
User | {} or Partial, or you need to redefine the User type 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
Username is left undefined, while the type annotation is saying it can't be undefined. – Ian Liu RodriguesAnswer
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.
Code Snippets
type User = {
Username: string;
Email: string;
}
const user01 = {} as User;
const user02 = <User>{};
user01.Email = "foo@bar.com";Context
Stack Overflow Q#45339065, score: 514
Revisions (0)
No revisions yet.