The object in Typescript – part 1

Hi, there is a few ways to use types to describe objects in Typescript, for example if we have a normal Javascript object:

  let fullName = {
    lastName: 'Rojas'
  }

  console.log('a.b---->', fullName.lastName)

We can access to that property without problems:

Now there is a way to declare a object type in TypeScript:

  let fullName: object = {
    lastName: 'Rojas'
  }

 console.log('a.b---->', fullName.lastName)

Ups! we can’t access to the object property:

The object is a little narrower than any, but not by much. The object don’t tell us a lot about the value it describes.

In that case we can let TypeScript do its thing like:

We removed the object and look how automatically Typescript define lastName as string type:

Nice, other example:

  let b = {
    c: {
      d: 'Cristina Rojas'
    }
  }

  console.log('my Data ----->', b.c.d)

Result:

So, we can either let TypeScript infer our object’s shape for us, or explicitly describe it inside curly braces like this:

Result:

By Cristina Rojas.