How to "type" nested objects? (Typescript)

Asked

Viewed 652 times

1

I have the following example object:

const types: any = {
            car: { full: 'fullString', empty: 'emptyString' },
            plane: 'myString',
};

I’m trying to get a guy on types but the nested object (car), He doesn’t think he’s the right guy. Ex:

const types: {[key:string]: string} = {
                car: { full: 'fullString', empty: 'emptyString' },
                plane: 'myString',
    };

How should I type for him to consider the object nestled?

1 answer

2


If you are using typescript and want to make a better use of types, especially for objects, the best thing to do is to use an interface, example:

interface MinhaInterface{
   car: {
     full: string,
     empty: string
   },
   plane: string
}

And then use it as follows:

const types: MinhaInterface = {
  ...
}

This way you will get help from Intellisense which will tell you if you have forgotten any property and also if the value passed to a property is different than expected.

With the example above you can make a refactor and transform for example the object that car receives as value in a proper interface in case of need, example:

interface Car{
   full: string,
   empty: string
}

interface MinhaInterface{
   car: Car,
   plane: string
}

The problem with your code is that passing [key:string]: string as type you telling for what type of your variable is an object composed of a type key string and that each key may contain a value that must also be string, which will not always be true in your case since car is your turn an object. If you want to do in your way what can be done is:

const types: {[key:string]: string | object} = {
    car: { full: 'fullString', empty: 'emptyString' },
    plane: 'myString',
}

With this the compiler should not point out errors since now your keys can contain type values string or object, but honestly it makes no sense to use typescript if you will not make use of the types in the best possible way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.