Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Typescript Interface Not Render In Javascript

I have been working with TypeScript for a week now. I am stuck on interfaces; here I am unable to figure out how TypeScript converts an interface into JavaScript, as it does not appear in the JavaScript code after compiling.

TypeScript

interface IPerson { 
  firstName: string;
  lastName: string;
  sayHi: () => string; 
}

var customer: IPerson = { 
  firstName: "Tom",
  lastName: "Hanks", 
  sayHi: (): string => { return "Hi there" } 
} 

console.log("Customer Object ") 
console.log(customer.firstName) 
console.log(customer.lastName) 
console.log(customer.sayHi())  

JavaScript

var customer = {
firstName: "Tom",
lastName: "Hanks",
sayHi: function () { return "Hi there"; }
};
console.log("Customer Object ");
console.log(customer.firstName);
console.log(customer.lastName);
console.log(customer.sayHi());
like image 467
TAHA SULTAN TEMURI Avatar asked Jul 18 '26 19:07

TAHA SULTAN TEMURI


1 Answers

Concepts such as interfaces don't exist in plain JavaScript. Interfaces only exist in TypeScript where they are used to guarantee that usages and definitions adhere to the contract.

interface Post {
  id: string;
  title: string;
}

The above definition is used by the compiler to guarantee that the contract is respected:

const goingToNewYork: Post = {
  id: '123-455-222-111',
}

enter image description here

Once the job of type checking is done, typescript simply compiles ts to plain javascript (which omits declarations).

  • Declarations can be outputted to separate files, normally known as d.ts: https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html
like image 150
Hitmands Avatar answered Jul 20 '26 08:07

Hitmands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!