Adding Types in Typescript

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we add types to a regular function “computeTip”.   Javascript does not yet have types, so we use Typescript which adds types to Javascript.  We create a new typescript file called app.ts …

types in typescript

We specify that computeTip is adheres to the “Function” interface.  That the input “amount” is a “number” type.  And that the function returns a “number”.

To run, you have to have Node.js and the typescript compiler tsc installed as described in previous tutorial.  Then you can do …

running typescript

If you are using a typescript knowledgable editor such as Visual Studio Code, it will warn you when you are using the wrong types…

type warning

Instead you have to explicitly convert to string and specify string as the return type …

correct type conversion

Array of types

To specify the types of an array elements, you have two ways of doing it …

array of types

The second way is using generics.

You can have types of your own class such as …

types of class





Share This