Typescript empty object for a typed variable

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

    Really depends on what you're trying to do. Types are documentation in typescript, so you want to show intention about how this thing is supposed to be used when you're creating the type.

    Option 1: If Users might have some but not all of the attributes during their lifetime

    Make all attributes optional

    type User = {
      attr0?: number
      attr1?: string
    }
    

    Option 2: If variables containing Users may begin null

    type User = {
    ...
    }
    let u1: User = null;
    

    Though, really, here if the point is to declare the User object before it can be known what will be assigned to it, you probably want to do let u1:User without any assignment.

    Option 3: What you probably want

    Really, the premise of typescript is to make sure that you are conforming to the mental model you outline in types in order to avoid making mistakes. If you want to add things to an object one-by-one, this is a habit that TypeScript is trying to get you not to do.

    More likely, you want to make some local variables, then assign to the User-containing variable when it's ready to be a full-on User. That way you'll never be left with a partially-formed User. Those things are gross.

    let attr1: number = ...
    let attr2: string = ...
    let user1: User = {
      attr1: attr1,
      attr2: attr2
    }
    

提交回复
热议问题