Typescript syntax

Asked

Viewed 370 times

5

I am studying Typescript but do not understand what this example means:

interface Person {
    firstname: string;
    lastname: string;
}

function greeter(person : Person) {
    return "Hello, " + person.firstname + " " + person.lastname;
}

I don’t understand the use of interface. From what I understand, it defines a kind of new "type" of variable, which in this example is being used in the excerpt person : Person (another excerpt I don’t understand), but in the compiled script it doesn’t seem to have any effect:

function greeter(person) {
    return "Hello, " + person.firstname + " " + person.lastname;
}

Compiling only the code below, the result is the same. Could anyone help me understand this point of syntax?

function greeter(person) {
    return "Hello, " + person.firstname + " " + person.lastname;
}

1 answer

8


Typescript is a superset of Javascript, the purpose of the language is to provide strong typing for programmers accustomed to C# to write Javascript in a more "comfortable" way. Typescript code is not executed at the end, it must be "compiled" and the result will always be Javascript code.

The use of the interface in the example you quoted, "exists" only while you are writing Typescript code:

interface Person {
    firstname: string;
    lastname: string;
}

This code will be useful for the compiler as well as the Visual Studio IDE to understand the object person has only members firstname and lastname

function greeter(person : Person) {
    return "Hello, " + person.firstname + " " + person.lastname;
}

What is that for? To avoid making mistakes, include support for Intellisense and a range of features similar to those that Visual Studio offers with C# (renaming variables, going to a member’s definition, etc).

In this example, unlike Javascript, in Typescript the compiler would not allow us to attempt to access an undeclared member of the object person:

person.age; // isso retornaria um erro de compilação

An advantage that I experienced and really liked was the possibility to download definition packages from existing libraries (look at nuget for Definitelytyped typescript) like jquery, googlemaps api, to be included as a reference in Typescript files. I found wonderful the experience of using the Google Maps API with Intellisense, without having to fetch the documentation every moment.

In short, the purpose of Typescript is to maintain Javascript syntax (it is possible to write only Javascript code even on TS) including strong typing with class writing support, with inheritance and polymorphism while we are writing our code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.