Categories
TypeScript Answers

How to create an object based on an interface file definition in TypeScript?

To create an object based on an interface file definition in TypeScript, we can create a class that extends the interface.

For instance, we write

interface IModal {
  content: string;
  form: string;
  //...
  foo: (bar: string) => void;
}

class Modal implements IModal {
  content: string;
  form: string;

  foo(param: string): void {}
}

to create the IModal interface with some fields.

Then we create the Modal class that has the fields listed in IModal.

Then we can use new Modal() to create a new Modal instance.

Conclusion

To create an object based on an interface file definition in TypeScript, we can create a class that extends the interface.

Categories
Nodejs TypeScript Answers

How to extend Express request object using Typescript?

Sometimes, we want to extend Express request object using Typescript.

In this article, we’ll look at how to extend Express request object using Typescript.

How to extend Express request object using Typescript?

To extend Express request object using Typescript, we can declare our own type definition for the request object.

For instance, we write

custom.d.ts

declare namespace Express {
  export interface Request {
    tenant? : string
  }
}

to add the tenant property to the type definition of the request object.

Then we include custom.d.ts in tsconfig.json so the TypeScript compiler will pick up the type.

Finally, we can add the tenant property to the request without TypeScript errors like

router.use((req, res, next) => {
  req.tenant = 'tenant'
  next()
})

router.get('/who', (req, res) => {
  res.status(200).send(req.tenant)
})

Coclusion

To extend Express request object using Typescript, we can declare our own type definition for the request object.

Categories
JavaScript Answers TypeScript Answers

How to set the data type of Axios mock using Jest TypeScript?

Sometimes, we want to set the data type of Axios mock using Jest TypeScript.

In this article, we’ll look at how to set the data type of Axios mock using Jest TypeScript.

How to set the data type of Axios mock using Jest TypeScript?

To set the data type of Axios mock using Jest TypeScript, we can use the jest.Mocked<typeof axios> type.

For instance, we write

import axios from 'axios';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

//...

mockedAxios.get.mockRejectedValue('error');
mockedAxios.get.mockResolvedValue({ data: {} });

to set the type of mockedAxios to jest.Mocked<typeof axios> with as.

We mock Axios with jest.mock('axios').

And then we can call mockedAxios.get.mockRejectedValue or mockedAxios.get.mockResolvedValue to set the mocked resolve or reject value of the promise returned by axios.get.

Conclusion

To set the data type of Axios mock using Jest TypeScript, we can use the jest.Mocked<typeof axios> type.

Categories
JavaScript Answers TypeScript Answers

How to fix the “Cannot find name ‘it'” error in Jest TypeScript?

To fix the "Cannot find name ‘it’" error in Jest TypeScript, we need to install a few packages and change the test config.

First, we install the Jest TypeScript packages with

npm i npm install jest @types/jest ts-jest

Then in the jest.config.js file at the root folder, we add

module.exports = {
  roots: ['<rootDir>/src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}

so Jest can pick up test files and module files in the tests.

Then in tsconfig.json, we have

{
  "compilerOptions": {
    //...
    "types": ["reflect-metadata", "jest"],
    "typeRoots": ["./types", "./node_modules/@types"]
    //...
  },
  "exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"],
  "include": ["./src/**/*.tsx", "./src/**/*.ts"]
}

so that the TypeScript compiler can pick up the TypeScript source code files in the folder by putting the include array.

And we exclude paths of non production source files with the exclude option.

We add 'jest' to types so that the type definitions of Jest is picked up by the TypeScript compiler.

Categories
TypeScript Answers

How to implement class constants with TypeScript?

Sometimes, we want to implement class constants with TypeScript.

In this article, we’ll look at how to implement class constants with TypeScript.

How to implement class constants with TypeScript?

To implement class constants with TypeScript, we can use the readonly keyword.

For instance, we write

class MyClass {
  readonly myReadOnlyProperty = 1;

  myMethod() {
    console.log(this.myReadOnlyProperty);    
  }
}

to add the myReadOnlyProperty class constant and set it to 1.

If we try to reassign it to another value like

const m = new MyClass()
m.myReadOnlyProperty = 2

then we’ll get a TypeScript compiler error.

Conclusion

To implement class constants with TypeScript, we can use the readonly keyword.