Typescript empty object for a typed variable

前端 未结 5 580
你的背包
你的背包 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:39

    Note that using const user = {} as UserType just provides intellisense but at runtime user is empty object {} and has no property inside. that means user.Email will give undefined instead of ""

    type UserType = {
        Username: string;
        Email: string;
    }
    

    So, use class with constructor for actually creating objects with default properties.

    type UserType = {
      Username: string;
      Email: string;
    };
    
    class User implements UserType {
      constructor() {
        this.Username = "";
        this.Email = "";
      }
    
      Username: string;
      Email: string;
    }
    
    const myUser = new User();
    console.log(myUser); // output: {Username: "", Email: ""}
    console.log("val: "+myUser.Email); // output: ""
    

    You can also use interface instead of type

    interface UserType {
      Username: string;
      Email: string;
    };
    

    ...and rest of code remains same.


    Actually, you can even skip the constructor part and use it like this:

    class User implements UserType {
          Username = ""; // will be added to new obj
          Email: string; // will not be added
    }
    
    const myUser = new User();
    console.log(myUser); // output: {Username: ""}
    

提交回复
热议问题