Home > Blockchain >  How to cast a type to an object without filling the fields beforehand?
How to cast a type to an object without filling the fields beforehand?

Time:10-02

Suppose I have this interface,

interface Obj {
  name: string
  bio: string
}

And I apply this type as so,

const obj: Obj = {}

But it tells me to fill name and bio fields beforehand. I don't want to do that as in my next case the types can be very long. The fields in obj are guaranteed to be present before the app load. I also don't want to use Partial<Obj> as I have to check each of the fields if they exist.

How do I cast a type to an object without filling the fields beforehand?

CodePudding user response:

You can simply cast your initial value to Obj with the keyword as:

const obj: Obj = {} as Obj

But you are aware of taking a risk, that if your initial object is not filled with the expected properties, you may have a runtime error.

CodePudding user response:

interface Obj {
  name: string
  bio: string
}

Here you are guaranteeing that any object assigned Obj type will have name and bio field. And, none of them can be undefined.

When you assign an empty object to Obj, it will complain because you are breaking the contract. And, Typescript isn't shy about it :)

Type '{}' is missing the following properties from type 'Obj': name, bio

Typing helps other developers to make mistakes like this inadvertently. If you wanted to assign empty object to the interface. You will have to tell that all fields are options. They may or may not be available. So, you define your interface like this:

interface Obj {
  name?: string
  bio?: string
}

const obj: Obj = {} // no error!

And, anyone using this will also be careful.

If you do not have control over the interface. Partial makes a very good case here. It effectively does the same thing as I have done. So, if a method returns a Partial the caller knows it may have missing attributes.

  • Related