Typescript empty object for a typed variable

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

    If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:

    type User = {
        Username?: string;
        Email?: string;
    }
    

提交回复
热议问题