Hi dev fellows,

In this post I want to talk about something very useful in TypeScript that might lead to issues if not properly used: Interfaces.

While it can be very handy for C# (or Java) developers to go to TypeScript, there is something we have to care about : Interfaces.
We need to know what they really are, to prevent some issues.

What is a TypeScript interface ?

An interface, in TypeScript, is a contract for the structure of any JavaScript object. It is very useful, because it allows the developer to use productivity tools like  authoring/compile-time code check.

This slideshow requires JavaScript.

It allows you to know, way before runtime, you assigned some values to property that are not expected. In plain old JS, it is totally valid! However, you probably don’t expect some values to be strings or numbers or vice-versa.

Interfaces are massively used in TypeScript, and really they are nothing more than a definition. They are the main things we find in the .d.ts files that allow you to have these productivity tools for you own APIs but also for many third party ones. Almost every popular library has its .d.ts file(s) : Angular, React, jQuery, Lodash, Moment, …

There is no spoon !

-Do not try and bend the spoon. That’s impossible. Instead only try to realize the truth.
– What truth?
– There is no spoon.

— The Matrix

Actually there is something you absolutely need to realize: Interfaces don’t exist, they are only a useful trick in TypeScript. Interfaces are not a JS thing.

Let’s take a look at the JS file generated for our interface

This slideshow requires JavaScript.

In the JavaScript that will be executed on the browser, there is no trace of the IMyObject (except maybe the .js.map file).

* The content of the generated JS file may vary according to your TypeScript configuration.

 

Errors at runtime

It means that, if you mistakenly fool TypeScript, it is still possible to have errors at runtime, let’s take the case where we get serialized JSON from a remote endpoint, We cannot really ensure at authoring time, what will be returned by the server at runtime. However, we want our code to be checked as any other part, you will probably write code like this

sample_pnpjs

The IlistInfo is an interface I defined. However, let’s imagine (very very unlikely 😉 hum…) I made a typo in the interface, TypeScript trust me and doesn’t complain about my mistake. However, there is one !

pnpjs_typo

pnpjs_typo_output

Conclusion

You can see at runtime, there was something unexpected. You have to play the TypeScript game fairly to be very efficient, and be sure of what you put in your interfaces if the data structure will be serialized or deserialized.  Be sure of your interfaces when their structure must strictly follow an “external” schema, especially take care of the typos 😉

Hope that will be helpful

See you,
Yannick

Advertisements