Handle javascript native objects with TypeScript

When working with JavaScript code that doesn’t have any TypeScript types defined, we can still handle the objects by creating TypeScript types that describe their shape.

For example, suppose we have the following JavaScript object:

const myObject = {
  name: 'John',
  age: 30,
  hobbies: ['reading', 'hiking'],
  sayHello: function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

To handle this object in TypeScript, we can create a TypeScript interface that describes its properties and methods:

interface MyObject {
  name: string;
  age: number;
  hobbies: string[];
  sayHello: () => void;
}

Now we can use this `MyObject` interface to handle the `myObject` variable in TypeScript functions:

function greetPerson(person: MyObject) {
  person.sayHello();
}

greetPerson(myObject);

This way, we can ensure that we’re working with objects that have the expected properties and methods, and get the benefits of TypeScript’s type checking and code completion.

Note that if the JavaScript object has optional properties, we can mark them as optional in the TypeScript interface using the `?` operator:

Written on April 5, 2023