Syntax TypeScript

4

I'm studying TypeScript but I do not understand the meaning of this example:

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

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

I do not understand the use of interface . So I understand, it defines a kind of new variable type, which in this example is being used in the person : Person excerpt (another part I do not understand), but in the compiled script it does not seem to have any effect:

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

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

function greeter(person) {
    return "Hello, " + person.firstname + " " + person.lastname;
}
    
asked by anonymous 31.03.2014 / 15:56

1 answer

7

TypeScript is a superset of Javascript, the goal of the language is to provide a strong typing for developers who are accustomed to C # to write Javascript in a more "comfortable" way. The TypeScript code does not run at the end, it must be "compiled" and the result will always be a Javascript code.

Using the interface in the example you cited, "exists" only while you are writing the 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 that the person object has only members firstname and lastname

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

What's the use? To avoid making mistakes, include intellisense support and a range of features similar to the ones Visual Studio offers with C # (rename variables, go to member 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

One advantage I experienced and enjoyed was the ability to download existing library definition packages (search the DefinitelyTyped typescript nuget) as jquery, googlemaps api, to be included as a reference in TypeScript files. I found the experience of using the Google Maps API with intellisense a wonder, without having to go to the documentation at any time.

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

    
31.03.2014 / 16:19