TypeScript
Setup TypeScript, Eslint, Jest and Prettier
Refer to here.
Narrowing
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
operatorin
operatorinstanceof
operator
Please refer to the official documentation for the details.
Declaration Merging
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
The folder path must be
/path/to/<MODULE>/index.d.ts
forts-node
to work properly.In
tsconfig.json
, updatecompilerOptions.typeRoots
to include the custom "types" folder.Done. TypeScript will acknowledge that
req.log
is aLogger
from now on.
Last updated