[TS] - custom type in typescript

Truong Bui

Published on: Last updated:

ts tips

TABLE OF CONTENTS

  1. Problem
  2. Solution

Problem

We install the lodash , but it supports only javascript , how to use it in typescript ?
File name: source-root/src/index.ts
import { isString } from 'lodash';
													^^^^^^ : Could not find a declaration file for module 'lodash'. '.../node_modules/lodash/lodash.js' implicitly has an 'any' type.
console.log(isString(null));
Of course, we can install the type definition for lodash by npm i --save-dev @types/lodash . But in this post we will create our own type definition for lodash.

Solution

We need to create lodash.d.ts file.
File name: source-root/types/lodash.d.ts
declare module 'lodash' {
	export function isString(value: any): boolean;
}
Look into tsconfig.json file
File name: source-root/tsconfig.json
{
	"compilerOptions": {
		"strict": true
	},
	"include": [
		"./src"
	]
}
As you can see typescript can only look for types definition in src . So we need to add types folder to include section.
File name: source-root/tsconfig.json
{
	"compilerOptions": {
		"strict": true
	},
	"include": [
		"./src",
		"./types"
	]
}
Now run tsc command. Woah, no errors 🎉.
Note: You can use typeRoots to specify the folder that contains the type definition. But I won't recommend it. Because it will override the default type definition folder.
INFO:
You can try tsc --traceResolution . You will see how typescript resolve the modules.

You will see something like

== Resolving module 'lodash' from 'source-root/src/index.ts'. ==

And

== Module name 'lodash' was successfully resolved to 'source-root/types/lodash.d.ts'. ==

Hope you find this article useful. If you have any questions, please let me know in the comment section below. 👇