[TS] - custom type in typescript
Truong Bui
Published on:
•
Last updated:
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));
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;
}
File name: source-root/tsconfig.json
{
"compilerOptions": {
"strict": true
},
"include": [
"./src"
]
}
File name: source-root/tsconfig.json
{
"compilerOptions": {
"strict": true
},
"include": [
"./src",
"./types"
]
}
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. 👇