Home > Software engineering >  how to define function within an object you make in typescript
how to define function within an object you make in typescript

Time:10-01

I have written the following object in typescript, which I need for a stub in unit testing (I know the values/function definitions make no sense but it's just a stub):

    const obj = {
      isEmpty: true,
      testName: 'unitTest',
      getTime: () => 5,
      success: () => {},
      fail: () => {},
      wait: () => {},
    };

getTime,success,fail and wait are supposed to be functions, but when I hover over them in VSCode, they are given as properties (like isEmpty and testName). Is there any way I can make it so they are strictly recognised as functions? (this is important later on in the unit test)

CodePudding user response:

You can define a type for obj like this. You editor should recognize it as functions now.

type objType = {
  isEmpty: boolean;
  testName: string;
  getTime(): number;
  success(): void;
  fail(): void;
  wait(): void;
};

const obj: objType = {
  isEmpty: true,
  testName: "unitTest",
  getTime: () => 5,
  success: () => {},
  fail: () => {},
  wait: () => {},
};

example

Example in Typescript playground

  • Related