TypeScript allows us to declare the shape of our types, variables and functions in separate files (for globals and/or modules). By using, the extension .d.ts the TypeScript Compiler/Linter can use these declarations in your project.
If you happen to be writing a library or working on a large project, this might be a good option. Today we will declare our types inline and at the head of our file.
// this function will return a stringdeclarefunctionparseString(str:string):string;// this var will be a numberdeclarevar myNum:number;// this var will be a stringdeclarevar name:string;// hey look an interface we can use of contact infodeclareinterfaceContactInfo { firstName:string; lastName:string; email:string; phone:string;}// the shape of a Cat classdeclareclassCat { name:string; breed:string; age:number;// methods for collecting and destroyingcollect(name:string, breed:string, age:number):voiddestroy(id:number):boolean}export {}
@types
When using third-party libraries like Express, Sequelize or Mongoose it can be annoying and frustrating trying to determine what our Types should be.
// note the imports used in node for typescript import express from'express';import dotenv from'dotenv';dotenv.config();constapp:express.Application=express();constport:number|string=process.env.PORT||3001app.get('/', (req:express.Request, res:express.Response) => {res.send('Wow I just wrote so much more code to accomplish this than I would with JavaScript')})app.listen(port, ():void=>{console.log(`"Typing" too much on port: ${port}`)})
Lucky for us the fine folks at Definitely Typed have created a repo of type declarations that can be installed via npm for most of the libraries that are widely used.
$npmi--save-dev@types/express@types/dotenv
Once installed, we can basically write normal javascript while implementing the Type guards of TS... making the example above look like this:
import express from'express';import dotenv from'dotenv';dotenv.config();constapp=express();constport:number|string=process.env.PORT||3001app.get('/', (req, res) => {res.send('Wow I just wrote so much more code to accomplish this than I would with JavaScript')})app.listen(port, () => {console.log(`Feeling better about this on port: ${port}`)})