3

I'm using TS Playground to learn TypeScript. What I found strange is that TypeScript doesn't generate a specific code for interfaces.

Example:

interface Person {
    id: number,
    fullName: string,
    sayHello: Function
}

let p: Person;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () {return "Hello from " + p.fullName;}

Will be translated to:

var p;
p.id = 123;
p.fullName = 'John Doe';
p.sayHello = function () { return "Hello from " + p.fullName; };

Is there an explanation why TypeScript doesn't generate any code for the interface ?

2 Answers 2

9

The TypeScript compiler performs a task called type erasure, which removes all types from the output (see note below). There are two key reasons for this:

  1. Type information cannot logically be represented in JavaScript
  2. Type information is intended for the compiler, not for runtime, so it isn't needed in the output

There have been some projects that intended to bring TypeScript's types to the runtime in order to perform runtime-type-checking, but there honestly wasn't a great appetite for this. Given we are moving from totally dynamic types at all times to static type checking at design/compile time, the leap may be big enough for the majority of people.

Types aren't the only thing that can be removed during compilation; another example is uninitialized class members, such as the name property in the example below, which you won't find in your JavaScript file.

class Example {
    public name: string;
}

const example = new Example();

console.log(example.name);

But most of the removals in your application will be types and ambient declarations.

The Note Below

All types are erased? There is some experimental support for emitting type information to be used with reflection, which you can try with the reflect-metadata package.

Sign up to request clarification or add additional context in comments.

Comments

2

Remember that TypeScript type system only exist in the scope of TypeScript itself.

In the end, it will be all pure JavaScript. The compiler is smart, it will only generate code when it's needed. That means that interfaces that contain only informations useful for TypeScript's type cheking and no real JavaScript code, will not result in any JavaScript code after compilation : There's simply no reason to generate unused code.

That's what happens with your code here : All the interface does is telling TypeScript which type should the variable be, without any actual JavaScript call. Once the compiler did its job to check the types, the interface has no reason to exist in JavaScript.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.