Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Hoisting

I am trying to understand hoisting in typescript. Does hoisting take place in Typescript and if yes, is there any difference compared to how it happens in Javascript.

eg: The code transpiles fine even though I declared interface after the function that is using it. Is it safe to assume it happens due to hoisting as a part of transpilation or else there is something else involved here.

getCarDetails({name: 'Xyz', topSpeed: 300})

function getCarDetails(carDetails: CarDetails) {

  console.log(carDetails.name);

  console.log(carDetails.topSpeed);

}

interface CarDetails {

  name: string;

  topSpeed: number;

}
like image 810
atish Avatar asked Mar 02 '23 15:03

atish


1 Answers

Does hoisting take place in Typescript

If your question is "Does TypeScript cause hoisting behaviour of the code?" then the answer is "No, it does not".

TypeScript does not exist at runtime, only at compile time. While "hoisting" is a concept related to running JavaScript code. TypeScript has as much of an impact on that as Notepad++ - whether you actually write your code there or not. That is to say, it has no influence over hoisting. It is the JavaScript engine that does it when it executes the code. Which is (potentially) far after the TypeScript compiler has finished with it.

However, if the question is "Does code written in TypeScript still exhibit hoisting behaviour?", the answer is "Yes, it does, but not in any way related to the fact that it is written in TypeScript". It would exhibit the same behaviour whether or not TypeScript is there.

The code transpiles fine even though I declared interface after the function that is using it. Is it safe to assume it happens due to hoisting as a part of transpilation or else there is something else involved here.

To be clear with terminology - "hoisting" refers to declarations being processed before running the code. This JavaScript code works due to hoisting:

fn();
function fn() {};

This TypeScript code does not use hoisting*:

const x: Foo = {id: 1};

interface Foo {
  id: number;
}

The type system only exists at compile time. Any TypeScript constructs like interfaces will be removed after compilation. Since they do not exist in JavaScript, it is an arbitrary and useless restriction to mandate interfaces be defined prior to using them.

The TypeScript code in the question compiles to the following JavaScript code:

getCarDetails({ name: 'Xyz', topSpeed: 300 });
function getCarDetails(carDetails) {
    console.log(carDetails.name);
    console.log(carDetails.topSpeed);
}

Thus only getCarDetails() will be hoisted when the code runs.


* const declarations are hoisted in JavaScript. This is the behaviour that leads to the temporal dead zone. This is just for the sake of completeness - it is not relevant in the given example.

like image 124
VLAZ Avatar answered Mar 16 '23 06:03

VLAZ