Adding Types with 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 …

Interface

Here we have defined an interface “Person” in Typescript…

The greeter function requires an parameter “user” that matches this interface. We create object “john” that matches that interface and pass it to the greeter function.

If the Person interface can have an optional property such as age, you can define it as such with a question mark…

The only problem with the Person interface now is that if we pass in an object with extra properties like “gender”, it would not fit the interface Person. If we allowed Person to have any other attributes after the ones that are specified, then you can do …

If you want the properties to be readonly precede it with the keyword “readonly” like this …

Now the function can not change the firstName as indicated by my editor warning of red squiggly line.

Instead of defining a named interface, you can specify the “shape” of the parameter “user” on-the-spot like this…

A class can implement an interface like this …

Typescript enum

Here we define an enum called “Month” and specified that “birthMonth” is of that type…

Note that when you output the enum, an integer 7 comes out. If it doesn’t make sense that August is 7, then you can assign your own integers like this …

other types

The “any” type can have any type.

But if you know in certain instances that the “any” type value will be of a specific type, then you can enforce it by …

The following statement is equivalent…

The “void” type can not have any type except for “undefined” or “null” types. A function can return a “void” type if it does not return anything …

A function can have a “never” type, if the function never terminates as in an infinite loop or more commonly throwing an exception…

And finally there is the “object” type …


Tags

Share This