Skip to content Skip to sidebar Skip to footer

What Is The Alternative Equivalent Of Javascript "prototype" In Typescript?

Typescript provides Object Oriented & Generic programming paradigms apart from Functional programming offered by Javascript. The keyword prototype is a very powerful and someti

Solution 1:

Typescript provides Object Oriented & Generic programming paradigms apart from Functional programming offered by Javascript.

No, JavaScript itself offers an object-oriented and generic programming model and can be used in the functional programming style as well (but isn't specifically designed to support it, like Haskell).

All TypeScript does is:

  • Add static type checking (this is its main purpose).
  • Support early adoption of certain proposed upcoming JavaScript features via the TypeScript compiler (for instance: TypeScript's compiler supported class syntax very early on).
  • Add some extra syntax on constructors which is unlikely ever to become a JavaScript feature: automatically copying parameters to properties.
  • Add "private" properties via a private keyword; JavaScript will have private properties soon, but not using the syntax TypeScript uses.

Everything else is JavaScript.

When I say "all" it does, that's not to diminish those things. Static type checking, in particular, can be extremely useful, particularly in large projects.

The keyword prototype is a very powerful and sometimes a dangerous tool. In general, I read that it simulates the inheritance aspect in Javascript.

prototype isn't a keyword, it's just the name of a property on constructor functions that refers to the object that will be assigned as the prototype of object created with the new keyword used with those constructors.

Inheritance isn't simulated in JavaScript. It's implemented with prototypes, see prototypical inheritance.

So preferably, what is the [closest] alternative of prototype in .ts?

That would be: prototype, either explicitly or indirectly via class. Again, TypeScript just adds a layer of static type checking and a couple of minor syntax additions. Everything else is just JavaScript.

Suppose if the answer is inheritance, then how to extend of implement the String kind of interfaces of JS into TS [as there can be lots of abstract methods]?

It's not very clear what you're asking here. You can either extend string:

class MyString extends String {
    // ...
}

...or add to String.prototype, ideally adding non-enumerable properties with functions assigned to them via Object.defineProperty:

Object.defineProperty(String.prototype, "myAddition", {/*...*/});

Post a Comment for "What Is The Alternative Equivalent Of Javascript "prototype" In Typescript?"