Typescript empty object for a typed variable

前端 未结 5 575
你的背包
你的背包 2020-12-13 22:53

Say I have:

type User = {
...
}

I want to create a new user but set it to be an empty object:

const user: User         


        
5条回答
  •  天涯浪人
    2020-12-13 23:31

    Caveats

    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. – jcalz

    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 Username is left undefined, while the type annotation is saying it can't be undefined. – Ian Liu Rodrigues

    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.

    type User = {
        Username: string;
        Email: string;
    }
    
    const user01 = {} as User;
    const user02 = {};
    
    user01.Email = "foo@bar.com";
    

    Here is a working example for you.

提交回复
热议问题