TypeScript
Last updated
Last updated
Refer to .
A variable can be declared to have multiple types. TypeScript will throw an error if the variable type might not fit an operation.
To eliminate the error, we can "narrow" down the type before the operation.
Typescript supports the following narrowing guards:
Truthiness
Equality
typeof
operator
in
operator
instanceof
operator
Declaration merging is an important technique to add custom fields to the existing interfaces.
Assume you are working with the HTTP server. If you want to add the logger to the req
object as req.log
, TypeScript will warn you that
Property 'log' does not exist on type 'IncomingMessage'.
To achieve that, you have to declare your own IncomingMessage
interface to merge with the default http.IncomingMessage
interface.
Declare your custom interface - ./src/types/http/index.d.ts
In tsconfig.json
, update compilerOptions.typeRoots
to include the custom "types" folder.
Done. TypeScript will acknowledge that req.log
is a Logger
from now on.
Please refer to for the details.
The folder path must be /path/to/<MODULE>/index.d.ts
for .