DEV Community

Cover image for 17 Compelling Reasons To Start Ditching TypeScript Now.
Mahmoud Harmouch
Mahmoud Harmouch

Posted on • Updated on

17 Compelling Reasons To Start Ditching TypeScript Now.

TL;DR

TypeScript is mid. Use Rust or C# for example if you wanna go 100% strict. Otherwise, stick to JavaScript + JSDOC + some tooling.

TypeScript has gained immense popularity as a reliable tool for developing complex applications. However, some developers have expressed their dissatisfaction with the language due to its tedious and annoying nature. This article aims to delve into the challenges of using TypeScript that can potentially complicate your projects unnecessarily. A significant downside is its time-consuming setup process which may lead to frustration among users. Furthermore, its strict type system often leads to lengthy development times and unwarranted errors cropping up frequently during coding sessions.

While there are benefits associated with TypeScript usage, it's crucial to weigh them against potential drawbacks before deciding whether or not you should use it for your next project. This piece aims to provide insights into these downsides so that you can make an informed decision about choosing the right language for your upcoming projects without any confusion or hesitation whatsoever!

But before going over its drawbacks, let's start with a gentle high overview of the language.

🆕 Update:

The creator of Svelte recently had a discussion with ThePrimeagen, which can be found in this video on youtube, where he made an impressive case for why Typescript may not be necessary. He explained how everything that Typescript offers can also be achieved using JS and JSDOC. This is significant news for developers like us who have been relying heavily on Typescript until now.

This discussion offers a new outlook on the dilemma of whether to employ pure Javascript or switch over to TypeScript for software development. The beauty lies in the fact that developers have complete autonomy and can choose based on their preferences, as both options offer error-checking capabilities through JSDoc without necessarily requiring TypeScript adoption.

This update brings about a fresh perspective regarding whether one should use plain Javascript or opt-in with TypeScript when developing software applications. Developers are free to choose between either option since they will still benefit from having their codes checked against errors by utilizing JSDoc instead of TypeScript.

👉 Table Of Contents (TOC).

What is Typescript?


TypeScript Logo.

TypeScript, an open-source programming language created and maintained by Microsoft, is commonly referred to as "JavaScript that scales" due to its object-oriented nature. Although some may argue it's a superset of JavaScript because of the added typing feature, I personally disagree with this notion. To illustrate the contrast between these two languages better, consider this straightforward code snippet:

// JavaScript
let name = "World!"
console.log(`Hello, ${name}`)

// TypeScript
let name: string =  "World!"
// Or simply
// let name =  "World!"
console.log(`Hello, ${name}`)
Enter fullscreen mode Exit fullscreen mode

Absolutely right! There's no difference between the two languages. TypeScript is a programming language that compiles statically and enables the development of comprehensible JavaScript code without strict typing requirements. It performs identical tasks to JavaScript and can be effortlessly utilized in both client-side and server-side applications. Additionally, any current JavaScript application will integrate seamlessly with TypeScript for an effortless transition experience.

The introduction of Typescript has brought a new level of ease and security to web development with its advanced typing system. However, the reality is that it falls short of delivering what it promises. Learning this language can be quite challenging as there are many complexities involved which may cause frustration for even seasoned developers who find themselves grappling with its complexities [0].

Why Do We Have TypeScript?

Image by Gordon Johnson from Pixabay.

🔝 Go To TOC.

Perhaps you're wondering, "What's the point? I could just use JavaScript." However, there is a compelling reason to type your variables: it allows for error detection during compilation rather than runtime. Consider this scenario - if you attempt to combine a string and number and save the outcome as a numeral value, an error of type will arise.

let x: number = 1;
let y: string = "2";
let z: number = x + y; // output: Type 'string' is not assignable to type 'number'.ts(2322)
Enter fullscreen mode Exit fullscreen mode

However, if you were to try this in JavaScript, the code would run without any errors:

let x = 1;
let y = "2";
let z = x + y; // output: 12
Enter fullscreen mode Exit fullscreen mode

It's evident that utilizing types can help in detecting errors at an early stage of development. TypeScript provides the option to include static types, which enables us to be more precise about our code and identify any possible problems. Consequently, this facilitates team collaboration and minimizes debugging time considerably.

However, there are still some situations where it falls. For instance, consider the following code snippet:

function push( arr : Array<string | number> ) {
    arr.push(99);
}
let foo : Array<string> = ['foo'];
push(foo);
Enter fullscreen mode Exit fullscreen mode

Even though we are appending a new string to an array, the TypeScript compiler fails to recognize the mismatch in data types and approves the code without any errors. This can potentially cause complications as it becomes challenging to detect type-related problems that may lead to runtime errors.

Despite my initial skepticism towards object-oriented programming, I have come to appreciate how valuable TypeScript is for those who prefer strong typing when working with objects. By utilizing the capabilities of its compiler, developers can create code that incorporates all aspects associated with OOP principles - something that JavaScript cannot provide on its own.

However, this doesn't mean you should automatically adopt TypeScript for every project you work on. As noted by their documentation [1], only a handful of companies possess resources comparable in size and scope as Microsoft's development team; therefore if your project requires significant scale or complexity then using Typescript might make sense but otherwise sticking solely with plain old Javascript would suffice even if starting out new at programming altogether!

Should I use It?

Image by Dave M from Pixabay.

🔝 Go To TOC.

The question at hand is whether TypeScript would be a fitting choice for your upcoming project. The answer can be found in its attributes. As previously mentioned, TypeScript offers the convenience of static typing, classes and interfaces that could significantly enhance productivity while developing extensive applications.

In my opinion, opting for TypeScript when collaborating on a project of medium to large scale with numerous developers could potentially yield positive results. However, it is important to note that this may not always hold true. The advantages associated with utilizing TypeScript are as follows:

  • Static Typing: This is a pretty straightforward one. It means you can catch errors at compile time before your code even runs. This makes code more predictable and easier to debug. But, as we saw previously, it is not always the case

  • Type Inference: TypeScript can often infer the types of variables, which means you don't have to declare them explicitly. This can make your code more concise and easier to read. However, this also can be achieved with JavaScript and JSDoc.

  • IntelliSense: This is a feature of Visual Studio Code that provides autocomplete suggestions based on the types of variables. This can, again, make your code easier to write and less error-prone. However, IntelliSense is not tidily coupled to TypeScript but is also supported in JavaScript [2].

In summary, our code is now more precise, thoroughly documented, and robust with superior quality. Nevertheless, upon implementation, you may discover that your code is less readable along with other concerns which we will delve into shortly. Therefore, before incorporating TypeScript in your project it's imperative to thoughtfully evaluate if its suitability aligns with the goals of your project.

Issues With Typescript.

Most Disliked Aspects of TypeScript by State of JS.

In the upcoming sections, we shall delve into a compilation of reasons why I have been increasingly abandoning Typescript. Despite its strength as a programming language, there are significant limitations that compel me to revert back to JavaScript with greater frequency.

1. The Learning Curve.

A steep learning curve (Image by author).

🔝 Go To TOC.

Learning Typescript can be a challenging and time-intensive process. To effectively use this language, one must possess proficiency in both JavaScript and type systems. This requires investing significant effort into comprehending the complexities of these structures as well as their interaction with JavaScript code. Even seasoned developers may struggle to grasp such concepts, making it an enormous obstacle for any fresh development endeavor.

Furthermore, Typescript presents some peculiarities that may pose challenges in implementation. Even seasoned developers cannot deny the fact that training oneself with this programming language can be a time-intensive endeavor. Teams must allocate significant resources towards training to ensure everyone is well-versed on current updates and optimal techniques. This could also prove problematic when attempting to comprehend pre-existing codebases written primarily in Typescript.

In short, the learning curve associated with Typescript can be quite steep and require significant time and effort to master.

2. Strict Type Checking System.

🔝 Go To TOC.

Another issue is that Typescript's type-checking system can often be overly strict and difficult to work with. This strict approach can lead to extra work and debugging time when dealing with complex types or features that don't fit into the type system cleanly. This extra effort can add up quickly over time and ultimately slow down development cycles.

The following implementation of a type-only bubble sort, utilizing an arithmetic utility type, is excessively rigid and poses challenges in terms of practicality [3]. While the comparator type may seem clever at first glance, it actually obscures some conditionals which can complicate debugging and maintenance. As such, this code proves to be especially challenging for beginners as they must possess a thorough comprehension of types and their respective functions.

type Test1 = BubbleSort<[1, 4, 1, 3, 2]>
//   ^?
type Test2 = BubbleSort<[4, 2, 1, 8, 5]>
//   ^?
type Test3 = BubbleSort<[-1, -9, 999, 50]>
//   ^?


//// ----------------BUBBLE SORT----------------

type BubbleSort<N extends number[]> =
  BubbleSortPass<N> extends Is<infer OnePass, number[]>
    ? BubbleSortPass<OnePass> extends BubbleSortPass<N>
      ? BubbleSortPass<N>
      : BubbleSort<OnePass>
    : never

type BubbleSortPass<N extends number[]> =
  N extends [Is<infer First, number>, Is<infer Second, number>, ...infer Rest]
    ? Rest extends number[]
      ? Rest extends []
        ? LessThan<First, Second> extends true
          ? [First, Second]
          : [Second, First]
        : LessThan<First, Second> extends true
          ? [First, ...BubbleSortPass<[Second, ...Rest]>]
          : [Second, ...BubbleSortPass<[First, ...Rest]>]
      : never
    : never



//// ---------------UTILITY TYPES---------------

type LessThan<A extends number, B extends number> = 
  IsPositive<A> extends true
    ? IsPositive<B> extends true
      ? A extends 0
        ? B extends 0
          ? false
          : true
        : B extends 0
          ? false
          : LessThan<Subtract<A, 1>, Subtract<B, 1>>
      : false
    : IsPositive<B> extends true
      ? true
      : `${A}` extends `-${infer PosAStr}`
        ? `${B}` extends `-${infer PosBStr}`
          ? StringToNumber<PosAStr> extends Is<infer PositiveA, number>
            ? StringToNumber<PosBStr> extends Is<infer PositiveB, number>
              ? LessThan<PositiveB, PositiveA>
              : never
            : never
          : never
        : never

type Is<T extends U, U> = T;

type Add<A extends number, B extends number> = StrictTupleLength<
  [...TupleOfLength<0, A>, ...TupleOfLength<0, B>]
>;

type Subtract<A extends number, B extends number> = 
  TupleOfLength<0, A> extends [...TupleOfLength<0, B>, ...infer Result]
    ? Result['length']
    : never;

type IsPositive<N extends number> = 
  `${N}` extends `-${number}` ? false : true;

// https://stackoverflow.com/a/70526775/16121252
type StringToNumber<T extends string, A extends any[] = []> =
  T extends keyof [0, ...A] ? A['length'] : StringToNumber<T, [0, ...A]>


/// Types the utilities rely on

type StrictTupleLength<T> = T extends { length: Is<infer L, number> }
  ? L
  : never

type TupleOfLength<
  T,
  L extends number,
  R extends T[] = [],
> = R['length'] extends L ? R : TupleOfLength<T, L, [...R, T]>;
Enter fullscreen mode Exit fullscreen mode

3. Verbosity And Lack Of Readability.

🔝 Go To TOC.

As I started my journey with Typescript, I first noticed how verbose the language was. It requires a lot of extra typing compared to JavaScript. This can be attributed to the rigid syntax and the numerous rules one must remember. This can be quite frustrating for those who are used to writing code quickly and efficiently in other languages.

The excessive verbosity of Typescript may pose a challenge when attempting to comprehend the language and troubleshoot code. This is due to the complexity involved in keeping track of various components within your program.

The language supposed to bring readability and clarity to the codebase obscures it instead. The code below is an example of documented TypeScript, which is incredibly bloated. This makes the code difficult to read and understand, which is one of the main arguments against using TypeScript.

class Rectangle {

  width: number
  length: number

  /**
   * Create a Rectangle instance.
   *
   * @param width - The width of the rectangle.
   * @param [length] - The length of the rectangle.
   */
  constructor(width: number, length: number = 20) {
    this.width = width
    this.length = length
  }

  /**
   * Calculate the area of a rectangle.
   *
   * @returns - The area of a rectangle.
   *
   * @example Correct usage.
   *
   * // Returns 200
   * calcArea(10, 20);
   *
   */
  calcArea(): number {
    return this.width * this.length
  }
}
Enter fullscreen mode Exit fullscreen mode

You'd have to add so many type annotations along with your code. Seriously, just use JavaScript. It's faster and simpler, and you don't have to worry about all that type of stuff as they are presented through JSDoc.

class Rectangle {
  width
  length

  /**
   * Create a Rectangle instance.
   *
   * @param {number} width - The width of the rectangle.
   * @param {number} [length] - The length of the rectangle.
   */
  constructor(width, length = 20) {
    this.width = width
    this.length = length
  }

  /**
   * Calculate the area of a rectangle.
   *
   * @returns {number} - The area of a rectangle.
   *
   * @example Correct usage.
   *
   * // Returns 200
   * calcArea(10, 20);
   *
   */
  calcArea() {
    return this.width * this.length
  }
}
const rectangle = new Rectangle("10")
Enter fullscreen mode Exit fullscreen mode
Image by author.

This example demonstrates that you can also achieve static type checking using only JS and JSDoc and enabling CheckJS in File > Preferences > Settings > search for "CheckJS" in VS Code. If you consider looking at the official core TypeScript codebase, you will notice an excessive amount of TSDoc comments used throughout the codebase. This shows that you should avoid using TypeScript whenever possible and rather stick to Javascript with JSDoc.

4. Lack Of Intuitive Syntax.

🔝 Go To TOC.

For those new to programming, understanding Typescript syntax can be challenging. The language uses conventions that may not be familiar to developers coming from other languages, making it difficult for them to read and comprehend the code.

Even after becoming comfortable with the language's syntax, beginners may still find errors hard to decipher due to its strict rules and conventions. For instance, variables must have a type declaration while each parameter in a function requires an assigned type - failing which will result in confusing error messages.

However daunting this might seem at first glance; patience is key when learning as these limitations can only be overcome by sticking with it. Despite all of this complexity though: remember that Typescript remains one of the most powerful tools available today for writing cleaner more efficient code- just give yourself time!

5. Lack of Compatibility.

🔝 Go To TOC.

Although TypeScript can be a valuable asset, it may not always integrate seamlessly with other tools. In my experience, I created a Lambda function for NodeJs and the project manager requested to edit it using AWS online editor. However, utilizing TypeScript would have necessitated transpilation which rendered this task unfeasible. This was unacceptable for the project manager's requirements; thus forcing me to revert back to traditional JavaScript code instead of TypeScript implementation.

Incorporating TypeScript into existing technologies or frameworks can present difficulties. If you're working with an outdated system that doesn't accommodate this language, manually converting your code to JavaScript becomes a requisite and time-intensive task. This scenario may prove complicated if you aren't proficient in the nuances of both languages, rendering it harsh as well.

So, don't assume that TypeScript will fit seamlessly into your existing workflow; Do your research and ensure that it will actually work with the tools you're using or you risk wasting valuable time and resources.

6. Low Productivity.

Image from istockphoto.com.

🔝 Go To TOC.

While coding in Typescript, one may experience a slower and more brutal process compared to the smoother flow of languages such as JavaScript or Python. This can be particularly annoying for developers who are used to quick and effective work with other programming tools - myself included.

When you are trying to rapidly prototype something during a Hackathon, the last thing you want is to deal with the extra overhead of Typescript. This can often lead to frustration and wasted time as you try to work around the limitations of the language.

Over time, Typescript can be quite frustrating, especially compared to other more rapid development languages. If you are looking to build something quickly, you would be better off using our beloved language, Javascript.

However, the question now is: what about the bugs in production? Typescript catches type bugs that would otherwise end up in production. But why is it common among Devs who are overconfident in their ability to write bug-free code?

7. False Promises.

🔝 Go To TOC.

In all honesty, TypeScript doesn't quite resonate with me as it seems to promise a one-size-fits-all solution for any JavaScript-related issue. It's attempting to surpass Javascript and become the primary language of choice in web development- an idea that I'm not particularly fond of. Personally, I prefer sticking with good old-fashioned Javascript without having everything altered by TypeScript's interference.

Although some may argue that the absence of typing in JS poses an issue, TS does not provide a solution. However, compiled languages such as Java, Rust, C, and C# have the ability to ensure strong typing both at compile time and runtime which is impossible for interpreted languages to achieve.

Some time ago, Deno - a javascript runtime that utilizes the V8 engine, Rust, and Tokio - narrated their experience with Typescript. They discovered it to be adding unnecessary complexity to the system, and make it slow. In their report, they offered an example that illustrated how difficult it was for them to gain insight due to the complexity of generating runtime code; this is contrary to what Typescript promises in terms of helping developers organize their codes. While there may be instances where such claims hold true, on other occasions its implementation can have negative effects instead.

8. Lack of Flexibility.

🔝 Go To TOC.

Typescript was developed to enhance the accessibility of JavaScript, and its popularity has surged in recent years. However, it comes with certain limitations that restrict developers from fully exploring the language's capabilities. In fact, TypeScript aims to shorten some of JavaScript's strengths while providing a false sense of security which can be detrimental for programmers who cannot utilize or experiment with all aspects of this powerful language as per their needs and desires.

Developers need to understand that this lack of flexibility does not make them better developers; indeed, it may even slow their development process and lead them away from truly understanding how JavaScript works and how to use it effectively. Having limited capabilities can potentially lead to the inability to utilize the full potential of JavaScript. If you want to become a great developer, you need to understand the true power behind JavaScript and all its features rather than settle for a lie from Typescript.

To truly excel as a developer, settling for a language that suppresses your creativity and hides its full potential is simply not an option. Embrace the versatility of JavaScript to unleash your true capabilities in coding. Only then can you reach new heights and become the great developer you aspire to be.

9. Giant Corporation Abuse.

🔝 Go To TOC.

Microsoft, a global giant in the tech industry, backs Typescript. As such, they have an inherent desire to promote their own interests and encourage developers to adopt their technology. Their marketing strategy for Typescript positions it as the ultimate language for JavaScript development - a claim that has been met with skepticism from some developer communities who view this approach as manipulative and limiting choice.

In addition, the support of major corporations can establish a setting that compels developers to comply with and adopt Microsoft's technology. This may slow innovation and result in an approach where coding solutions are limited to one standardized option. Ideally, developers should have access to various alternatives tailored to their specific requirements instead of being forced into utilizing products endorsed by corporate giants.

Microsoft's approach can lead to confusion among developers who may not be fully aware of the nuances of Typescript or its superiority over other programming languages such as JavaScript. Companies like Microsoft must provide precise information about their product in order to prevent any confusion or misinterpretation that could slow a developer from making an informed decision on what language would best suit their needs.

If you don't know yet, Microsoft has a long history of being an anti-open source and anti-Linux. In 2001, their CEO Steve Ballmer declared Linux a "cancer" [4]. The company sponsored SCO's copyright attack on Linux and claimed that Linux violated unnamed Microsoft patents. Microsoft also forced Linux-based Android vendors to pay for questionable patent claims.

One of Microsoft's biggest issues today is its involvement with Typescript. While the company has been trying to make success in recent years to improve its relationship with the open-source community, its history still casts a long shadow.

So, even though Typescript is a powerful programming language, it's important to note that a historically bad corporation backs it.

10. Clever Devs Abuse.

🔝 Go To TOC.

The issue with clever developers using Typescript is that they unnecessarily over-complicate the code. This leads to several problems, making code difficult to read, maintain, and debug. Additionally, it can cause issues with scalability and performance.

When clever developers use Typescript, they tend to prioritize crafting complex and convoluted code over producing efficient and impactful one. This may result in a significant amount of time being wasted on debugging and troubleshooting issues that could have been preemptively addressed.

Furthermore, clever developers may prioritize their own pride over the product itself. They may be too focused on creating complex solutions when simpler ones are available. This can lead to solutions that don't actually make the product better for users or customers.

It is crucial for developers to keep in mind that client/customer satisfaction should always be the ultimate objective. Any solution that fails to enhance the product or simplify user experience is not worth investing time and effort into. Instead of solely striving for personal gratification through their code, clever developers must concentrate on crafting solutions geared towards improving overall client/customer experience.

Let's all agree that just because "clever developers" use something doesn't mean it's a good tool. But if so many big open-source projects have moved to TS and told me that it made their development easier, I'll trust them, especially because it made mine much easier and less stressful.

11. Not A JS Superset.

🔝 Go To TOC.

One of the key selling points of Typescript is that it is a superset of javascript, meaning that every JavaScript program is a valid TypeScript program. However, in practice, this has not always been the case. And TypeScript is neither a subset nor a superset of JavaScript.

For example, a valid piece of JavaScript code may not be valid TypeScript code, such as the following:

let foo = {};
foo.bar = 42;
Enter fullscreen mode Exit fullscreen mode
Image by author.

12. Slower Compile Time.

Image by author.

🔝 Go To TOC.

One of the main challenges encountered while using Typescript is its slower compilation time, which becomes more evident when working on a large codebase. The TypeScript compiler lacks efficiency in optimizing codes compared to other compilers resulting in longer completion times for compile tasks. Consequently, this may lead to increased file sizes and prolonged waiting periods as one waits for the compiler's job to finish [5].

The primary reason for the delay in compiling is attributed to Typescript's statically-typed characteristic. This implies that the compiler has a more extensive workload compared to its counterpart for dynamically-typed languages such as JavaScript, resulting in prolonged compilation durations. Furthermore, unlike Babel, TypeScript's compiler lacks access to similar optimization tools which worsens this issue and ultimately hinders our productivity.

The process of compiling typescript code can be a tedious and time-consuming task, particularly when dealing with extensive projects. Deno maintainers have acknowledged that modifying files in cli/js leads to an incremental increase in compile duration which takes minutes, causing significant frustration [6]. As someone who has recently adopted this language, I can vow to the annoyance experienced while waiting for even minor changes to complete the compilation before repeating the cycle again. This is not only a main waste of time but also incredibly annoying.

While I acknowledge that TypeScript may appeal to those who prioritize type safety, personally, I believe the potential loss in productivity outweighs its benefits. Furthermore, similar results can be achieved through JSDoc and certain configurations on VSCode.

13. Additional Transpilation Step.

🔝 Go To TOC.

This issue is somewhat related to the previous one. As a JavaScript developer, you're probably used to transpiling your code with Babel. TypeScript introduces an additional transpilation step which can, unfortunately, introduce a bottleneck regarding development speed. It's true that the compiler can spot flaws and flag them before they can cause any damage, but this comes at the cost of having to wait for the entire codebase to be transpiled each time. This can be particularly frustrating for larger projects, where the compilation time can quickly add up.

Moreover, the TypeScript compiler has a tendency to produce code that can be perplexing or challenging to comprehend. This is due to its endeavor of ensuring type-safety in your code, which may lead to lengthier and more intricate variable names at times. While this approach isn't always unfavorable, it could pose difficulties for novice developers who haven't yet grasped the norms of TypeScript's syntax.

14. Lack of Performance.

🔝 Go To TOC.

In case you are writing in TypeScript, it is possible that your program's execution speed might be slower than anticipated. This could be attributed to the fact that the organization and structure of TypeScript is a subject of a performance cost during runtime.

By utilizing TypeScript, you are instructing the compiler to structure your code in a particular manner. However, this organization may lead to runtime performance issues. For instance, if you possess an extensive collection of objects, TypeScript will potentially generate a distinct variable for each object within that array. As such, whenever you access any of these objects individually later on during execution time requires searching through memory for its corresponding variable - resulting in significant overhead and suboptimal application performance overall.

15. Writing Unit Tests.

🔝 Go To TOC.

Writing unit tests in TypeScript can be a daunting task that demands precision. Unlike JavaScript, where passing an object with the appropriate properties suffices for testing purposes, TypeScript necessitates defining the type of every property within the given object. This process is time-consuming and often frustrating for beginners who are just starting out. Therefore, I personally opt to use JavaScript instead when crafting my unit tests as it saves me valuable time and effort while still yielding effective results.

Taking more time to define the various types and properties tends to slow my overall productivity. Additionally, it also complicates debugging and refactoring processes considerably. To illustrate this point further, if I need to alter just one property of an object utilized in a test scenario, then I would have no choice but to go back and modify both the type definition as well as the code for that particular test case. This added step could be avoided entirely had I been writing tests using JavaScript instead.

I understand why TypeScript requires this level of precision; It helps add an extra layer of safety during development, but it can sometimes be incredibly tedious and frustrating. For this reason alone, I will continue to choose JavaScript over TypeScript when writing unit tests.

16. Types Are Not That Useful.

🔝 Go To TOC.

If you have a background in statically typed languages such as Java, it's natural to believe that types are always advantageous. However, when working with JavaScript, the opposite may be true - types can sometimes slow progress rather than ease it. This is because JavaScript is an incredibly dynamic language where flexibility reigns supreme and rigid type systems often fall short of expectations.

Although TypeScript's type system can be advantageous, it may not always be necessary for the majority of JavaScript applications. In fact, many applications do not require additional safety that types offer and implementing them could result in unnecessary complexity without any significant benefits. Hence, opting to use plain JavaScript while developing an application might prove to be a more practical choice overall.

Furthermore, while TypeScript does support type inference - where the compiler attempts to deduce variable types based on usage patterns - this feature is not always reliable. When unable to determine a specific data type for a given variable or object property during compilation time; any becomes its default value instead of providing accurate typing information as expected by developers who use Typescript which ultimately defeats the purpose of utilizing such technology from start-to-finish in your project workflow.

let a: string;
let b: number;
let c;
a = 'Hello World';
b = 5;
c = a + b;
console.log(c);
Enter fullscreen mode Exit fullscreen mode
Image by author.

17. Heavier Tech Debt.

Image from istockphoto.com.

🔝 Go To TOC.

When it comes to tech debt, Typescript can be a major issue when a project's scope, tech stack, or architecture changes halfway through the process. The tech debt will increase as new features, and changes are added to the codebase. This can cause projects to become bogged down with tech debt that could have been avoided if an earlier assessment of the project scope and design plan had been conducted.

For example, suppose you decide to use Typescript for your project. You may think this language will be easier to maintain in the long run as it is more type-safe than other languages. However, halfway through the project, you realize that a different technology stack would be better suited for your particular project. You now have to go back and refactor all of your existing code from Typescript into the new technology stack, which can take considerably longer than if you had chosen the correct language from the beginning. As a result, you find yourself weighed down by tech debt that could have been easily avoided with proper planning at the start of your project.

However, you may argue that TypeScript is especially powerful when used in conjunction with other technologies. For example, Python and Go are two of the most commonly used general-purpose programming languages, while Bash is often used for smaller glue scripts. GNU Make is often misused as a project entry point (make run, make build, etc.).

I wouldn't say no to TypeScript, as this would force the always overworked operations team to write more quality code instead of fast hacks. But, at some point, this accumulated debt will reach critical mass, and it will be a long downtime just to write more fast hacks to get back up.

Therefore, it is important to assess your project scope and design plan thoroughly before deciding on which language to use to ensure that you do not end up with unnecessary tech debt further down the line.

For all the above reasons, type-only code is needlessly complicated to work with.

TypeScript Alternatives.

Image by author.

🔝 Go To TOC.

Ok, TypeScript is a fantastic tool/language, but it isn't the only one available to annotate your code. JSDoc is another option that Microsoft even uses in their core TypeScript code! So why argue over which tool to use? Let's choose what works best for our project.

But maybe you prefer not to use TypeScript or want to utilize JSDoc without compiling. No worries - there are plenty of options for type-checking and generating definitions in JavaScript. The top two contenders are Flow and JSDoc, with Flow being more popular yet less flexible than its counterpart alternative: JSDoc can be just as powerful when used correctly!

1. JSDoc.

Image by author.

🔝 Go To TOC.

JSDoc is a remarkable tool for documenting JavaScript that employs designated comments to generate documentation for your code. There are numerous compelling advantages of using JSDoc over TypeScript, which you may not be familiar with yet.

  • JSDoc prevents the necessity of a compiler, thereby simplifying code writing for your project. Moreover, JSDoc is frequently more lightweight than its TypeScript equivalents which enables you to concentrate on enhancing features and functionality without being bogged down by complex syntax issues or type-checking concerns.

  • JSDoc empowers you to prioritize the excellence and comprehensibility of your code. You can devote more attention towards perfecting its complexities and guaranteeing that it is accurately documented, without being affected by type checking or managing complex types. Moreover, JSDoc enables effortless integration of annotations into your codebase which clarifies each section's intended purpose - facilitating debugging and maintenance in the future with ease.

  • Writing your tests in vanilla JS and counting on JSDoc to provide you with the necessary types is a feasible approach. This method simplifies writing tests for code that doesn't prioritize types but still necessitates dependability. The versatility of JSDocs allows effortless customization of test cases, unlike TypeScript's inflexible type system which restricts possibilities. With JSDocs, customizing or modifying existing test scenarios becomes hassle-free; thus making it easy to tailor your assessments for specific situations or edge cases beyond what can be tested using TypeScript alone - an added advantage worth considering!

  • TypeScript requires annotations for documentation generation, which implies that JS/TSDocs is still a requisite. The difference in the amount of typing required between vanilla JSDoc and TypeScript + lightweight JSDoc is negligible.

  • One compelling reason to opt for JSDoc instead of TypeScript is its widespread IDE support. With JSDoc, you can avoid the need for extra dependencies and start documenting your code right away. Furthermore, this tool offers a robust documentation solution that goes beyond basic commenting features.

  • While TypeScript is a newer language and has gained quite a bit of popularity in recent years, many developers, me included, still prefer to use JSDoc. While it does not have all of the features of TypeScript(~90% of TS features, in my opinion.), it is still a very useful tool for us as web developers.

  • JSDoc is well established and the standard for JavaScript documentation. JSDoc is a widely accepted and adopted standard, making it much easier to find libraries that use JSDocs as opposed to TypeScript def files.

  • If you have to compile TypeScript into JavaScript, why not just use JS? Seeing as the means for achieving what you require already subsist, those familiar with JavaScript outnumber significantly those who know about TypeScript; finding personnel is simpler, and conjoining with existent teams is easier.

  • JSDoc adheres to the KISS principle by providing a simple yet powerful syntax that allows you to document your code briefly. With JSDoc, you can easily create documentation for your JavaScript code that's easy to read and understand.

As you can see, JSDoc offers so many advantages for writing hints for the IDE, and it would be wise for us as web developers to use it instead of TypeScript. It provides granular control over code, requires fewer steps when inserting a function name, and offers an independent standard that ensures everything functions properly.

Microsoft is promoting a narrative that TypeScript is the sole solution to resolve type problems, but this claim lacks validity. It's evident that Microsoft's motive behind such promotion arises from their financial gain rather than prioritizing developers' or users' needs and preferences.

To sum up, opting for JSDoc over TypeScript can prove advantageous in certain projects that don't necessarily demand type safety or when there are constraints on time and resources. Nevertheless, if your project involves complex logic or demands robust typing support, then TypeScript would still be the more cautious choice to guarantee meeting all requirements of your application.

2. Flow.

Image by author.

🔝 Go To TOC.

For those who aren't keen on utilizing TypeScript, Flow presents a good option. It functions as a static type checker for JavaScript and is capable of detecting errors in your code before execution. This feature holds immense power and can prevent numerous potential issues from arising.

Flow, like TypeScript, provides the capability of defining types for functions and variables. This feature can prove highly beneficial in sizeable projects where managing multiple types becomes a challenge. Additionally, Flow offers several unique features that are not present in TypeScript; one such example is its compatibility with React's propTypes.

The following are a few reasons why you might choose to use Flow over TypeScript:

  • Ease of use: Flow is more forgiving than TypeScript; it serves as a softer introduction to static types in JavaScript. With Flow, you can get up and running quickly without having to learn all the details of type checking right away. Additionally, because Flow uses a per-file opt-in methodology rather than requiring users to specify types everywhere upfront (as TypeScript does), it may be easier to add Flow into an existing project that doesn't already use static types.

  • With the backing of a massive corporation, Meta (previously known as Facebook) has crafted and maintained both React and Flow. As a result, these two resources integrate flawlessly with one another. The dedication that Meta shows towards maintaining these tools guarantees their ongoing support and enhancements - making them an optimal choice for us web developers who seek dependability in our work.

  • Flow is a more streamlined option for project integration, as it requires no supplementary dependencies. Unlike other type checkers that generate additional files like .d.ts, Flow doesn't create any extra files. Consequently, the environmental impact of using Flow is significantly smaller, and its incorporation into projects is much simpler and straightforward.

So if speed, accuracy, and simplicity are important to you, Flow might be the right choice for your project.

Which One Should You Choose?

🔝 Go To TOC.

The ultimate choice is yours to make: which option aligns best with your requirements and objectives? Flow offers a more extensive set of capabilities, whereas JSDoc presents itself as an equally feasible alternative. Regardless of the decision taken, both alternatives offer some level of type-checking and code generation for JavaScript projects - rendering them valuable considerations when working on large projects.

What's next for Javascript?

🔝 Go To TOC.

Recently, there are new suggestions to modify javascript. Although some of these ideas possess merit, one proposal stands out as a potential threat that could fundamentally alter the language we have come to know and rely on, today.

Static typing is something that has been proposed for javascript before, but it never really gained much traction [7]. However, with the recent popularity of languages like TypeScript and Flow, it seems like more and more people are open to the idea of adding types to javascript.

Personally, I'm not a huge fan of static typing. It can make code more verbose and difficult to read. But more importantly, it could make javascript less flexible and less forgiving.

Right now, javascript is a language that is easy to learn and easy to use. It's forgiving of mistakes, and it's flexible enough to be used in a variety of ways. But if we start adding types to the language, all of that could change.

There is a possibility that Javascript may adopt strict guidelines and rules similar to Java. Although this could be acceptable for certain individuals, I believe it would eventually render the language less approachable for novices.

So while I'm not opposed to the idea of static typing in general, I think it could be a disaster for javascript if it becomes mandatory. Let's hope that doesn't happen.

Conclusion.

🔝 Go To TOC.

In conclusion, being a humble developer, I think TS is good, but it's not always necessary or suitable for all projects. You can achieve bugproof and readable code with JavaScript along with JSDoc with type definition plus a few config tweaks in VS without needing another compiler. Ultimately though, I think this depends on the team you work with and what sort of project you're dealing with; if you need to do things quickly and work with junior developers, then a codebase built on a strong foundation of TypeScript may be necessary to ensure quality. Still, other approaches may be more suitable if you have proper code reviews and knowledge-sharing culture.

What is the rationale behind choosing TypeScript instead of javascript? From my perspective, when it comes to crafting error-free and comprehensible code that can be effortlessly maintained, nothing beats javascript. Although TypeScript does provide certain advantages, I am convinced that they pale in comparison to those offered by its predecessor -javascript.

In my honest opinion, going from JavaScript to Typescript is like transitioning from PHP to C#. The core concepts remain the same. However, you are adding a layer of type safety and an additional compilation step.

In the end, it is entirely up to you whether or not you hate Typescript. Nevertheless, if your goal is to create maintainable code that will keep your application running smoothly for years to come, mastering this language can prove invaluable. So don't give up hope just yet; continue coding and stay humble in regard to your own skills!

Bonus.

🔝 Go To TOC.

A collection of examples where TypeScript code results in undefined behavior:

References.

🔝 Go To TOC.

[0] Ryan Carniato. The Trouble with TypeScript Ryan Carniato, dev.to, Retrieved 2022-12-28.

[1] typescriptlang.org. Why Create TypeScript, typescriptlang.org, Retrieved 2022-12-28.

[2] visualstudio.com. JavaScript IntelliSense, visualstudio.com, Retrieved 2022-12-28.

[3] typescriptlang.org. Type-only bubble sort in TypeScript, typescriptlang.org, Retrieved 2022-12-28.

[4] theregister.com. Ballmer: 'Linux is a cancer', theregister.com, Retrieved 2022-12-28.

[5] stackoverflow.com. Typescript compiling very slowly, stackoverflow.com, Retrieved 2022-12-28.

[6] docs.google.com. Design Doc: Use JavaScript instead of TypeScript for internal Deno Code
, docs.google.com, Retrieved 2022-12-28.

[7] tc39 on Github. ECMAScript proposal for type syntax that is erased - Stage 1, github.com, Retrieved 2023-01-01.

Top comments (366)

Collapse
 
grantdotdev profile image
Grant Riordan

So, the article seems very biased from someone who is a huge advocate for JS, rather than pointing out actual flaws of the Typescript language.

I think the point of time consuming learning the language isn't valid and again opinionated. The syntax is not that different compared to JavaScript in reality. There are much more convoluted language syntax out there e.g Python, C++ to name but a few.

verbosity, is the whole point of any real strongly typed language. Without it, everything is simply dynamic types, making it difficult to know the schema of an object. Again it's the whole nature / reasoning for a typed language.

"The language uses conventions unfamiliar to developers coming from other languages and can make it difficult to read and understand the code."

In what way is syntax difficult. What are you comparing it with. You seem to be implying the syntax of JS is easy however TS really isn't that different.

Your testing point, I'm not following the scenario you're describing. Why would you wish to change the property of a type in a single test ? Are you referring to the value, or the type of the property ? If the latter I'd say you need to reassess the test / object needs

"For another thing, the type system in TypeScript is actually not that great."

What are you are actually referring to. Why isn't it that great. You simply state your opinion but don't explain why.

Collapse
 
leob profile image
leob

The problem with the article is that all of the 17 reasons are subjective and highly debatable. Other devs (the ones who do use/like TS) are adamant that it does have benefits for them. Who is "right"? No idea, this is an endless debate, but I've never seen any arguments from either side which totally convince me.

The only thing I see is that the "market share" and usage of TS are growing steadily, and by now it's becoming dominant ... so all I can conclude is that "TS must be doing something right". Just from looking at the stats and the rate of adoption I think TS is the future, whether we like it or not.

Collapse
 
gmartigny profile image
Guillaume Martigny

I'm not sure language adoption is a fair metric. Some people are pushing the use of TS in all circumstances regardless of real interest. As stated in the article TS might be a great solution for large project. But not for smaller team with less experienced devs.

Collapse
 
desone profile image
Desone

Yes, it is doing something which is keeping it in the market:
1- gives insight into the code to non-programmers and machines. Like AutoComplete tools in VS code and AI code analysers
2- it lets project managers micro-manage programmers and have a say on PRs and gives clues to organisation chart climbers.
3- restricts productivity and creativity so that companies are more likely to buy solutions than develop them. A good example can be using MS CRM rather than developing your own company tailor made system.
4 -by both ways cutting developers productivity and amplifying machine insights, it is facilitating machinized programming which is promoted by big techs and cloud provider and therefore they push for it.

Thread Thread
 
leob profile image
leob

Bold and interesting claims, not sure if they're backed up by facts and numbers :)

Thread Thread
 
desone profile image
Desone

I am leaving JavaScript world after 6 years of specialist JavaScript/Typescript development. There are too many brain washed idiot developers there, generating dirty code and with Typescript being enforced I am really tired of shit cleaning. Convincing people doesn't help as all big mouthes are brain washing hundreds per minute, is waste of time. Going into Python for a while.

Thread Thread
 
leob profile image
leob • Edited

I'm now using Typescript in earnest for the first time on a project, and I can honestly say it's a better experience than I expected - no major issues so far ... not saying that it "must" be used instead of straight JS on every project, but the experience so far is not too bad.

Good luck with Python, my favorite backend language is PHP (with Laravel as the framework).

Collapse
 
wiseai profile image
Mahmoud Harmouch

Thank you for your comment. I strive to provide quality content that is both informative and enjoyable to read. I am sorry to hear that you felt the article was not up to par in terms of your agreement with my opinion, which is ok.

Not only that, I am not quite sure if 17 flaws are not good enough to accurately convey my opinion in the language, but that doesn’t mean you should give up on my words altogether.

Furthermore, I think it is also important to keep in mind the context of my writing by taking the time to read my words carefully before responding. This will help you ensure that you don't miss any important information or points that I am trying to make.

Thank you again for taking the time to leave a comment. Have a good day/evening.

Collapse
 
brense profile image
Rense Bakker

So, you write a subjective article about typescript, because you dont like it and when a reader raises some valid questions, instead of giving a substantive response, you respond with something along the lines of: "if you dont agree with me you're stupid". Or: "I'm so smart you dont understand me".

It seems to me that your only perogative here is to start a flame war and I hope people will report your abuse.

Thread Thread
 
dancxjo profile image
Travis Reed

This was exactly my attitude when I started with TS. It's a very different mentality: when I learned JS, i got in the habit of runtime type checking. Getting rid of that, learning new idioms and considering compile time takes a lot of effort.

Thread Thread
 
brense profile image
Rense Bakker

Change always takes effort, nobody will dispute that and the road can be challenging depending on your history, but to write an article like the author did and put in this amount of effort to come up with unfounded reasons not to change... Thats a really bad attitude. Furthermore, you can tell what the authors attitude is by the responses they gave to some of the replies they got that disproved the reasons they gave.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

So, you write a subjective article about typescript,

I don't think there is anything wrong with writing a subjective article. In fact, it can be quite helpful to other developers who are considering using the language. By reading about another developer's experience with TypeScript, they can get a better sense of whether or not the language would be a good fit for them. Additionally, subjective articles can provide insights into how best to use TypeScript in order to get the most out of it.

I know that objectivity is key when writing about technical topics. Next time I will focus on more facts and data rather than personal opinion or being subjective.

because you dont like it and when a reader raises some valid questions, instead of giving a substantive response, you respond with something along the lines of "if you dont agree with me you're stupid". Or: "I'm so smart you dont understand me".

I mean, If I were to respond the way I wanted, I would look redundant. I would repeat the same points raised in the article, which is why I suggested reading it carefully. However, it is ultimately up to the reader whether or not they want to read it. I am not trying to prove that I am smarter than anyone but merely wanted to raise what seems to be important issues.

It seems to me that your only perogative here is to start a flame war and I hope people will report your abuse.

It is ok to remind people to use their damn minds.

Change always takes effort, nobody will dispute that and the road can be challenging depending on your history.

But, is it worth it? I say "it depends". The best answer comes from looking inward and determining if the change you seek is for betterment. If so, then making the effort to change will undoubtedly lead to a more positive outcome full of new opportunities and experiences.

but to write an article like the author did and put in this amount of effort to come up with unfounded reasons not to change...

Everyone has their own perspectives, however, it is important to remember the code of conduct of the platform when publishing an article. Everyone has the right to express their opinion in a respectful manner, and by doing so, it will help ensure that any conversation remains civil and respectful.

Peace!

Thread Thread
 
smolinari profile image
Scott Molinari

React is popular because Facebook has spent millions marketing it

There is in no way any evidence to prove this. In fact, as I see it, all they did was pay devs working on React to do a number of talks when React came out. The React docs have sucked almost to this day aka no real investment (they just got reworked and are somewhat better now). They did very little in terms of video tutorials either. They definitely had no paid advertisements.

What they did do is hit a nerve of the JS community at the time, namely the acknowledged hackery of using jQuery to update the DOM when data changed. Using the power of reactive programming, React turned the frontend world upside down for the positive. Now everyone can let their data do the walking. That is why React is so popular.

Scott

Collapse
 
aradalvand profile image
Comment deleted
Thread Thread
 
wiseai profile image
Mahmoud Harmouch

When you decide to become respectful, we can carry on our discussion in a more positive and productive manner.

Thread Thread
 
matronator profile image
Matronator

I actually agree with him...

Collapse
 
shadowfaax profile image
Shadowfaax

Using typescript instead of native JS, the gain is minimal compared to the flaws. FrontEnd is UI/UX, it's only an interface, you don't need to make it over-complicated.

The simple concept of typing everything is completely irrelevant in Front where you only need to display numbers and strings, and send forms.

The business layer is Backend and must stay in there.

Collapse
 
kukulaka profile image
Tanya Byrne • Edited

verbosity, is the whole point of any real strongly typed language. Without it, everything is simply dynamic types, making it difficult to know the schema of an object. Again it's the whole nature / reasoning for a typed language.

This! Also if you come from a background where you are used to using strongly typed languages, I would argue that picking up typescript is pretty straight forward. Point 16 seems like a "you" problem rather than an actual issue.

This article is highly subjective and I would argue kind of misleading and reductive to boot.

Collapse
 
wiseai profile image
Mahmoud Harmouch • Edited

Also if you come from a background where you are used to using strongly typed languages, I would argue that picking up typescript is pretty straight forward.

Why would someone switch from a strongly typed language to Typescript, which is less type-safe, probably not at all as @idleman pointed out. In my opinion, you better go for JavaScript if you are looking for forgiveness' sake. I mean, I don't get it. Is type safety a spectrum? I just don't see the point in sacrificing that level of safety for the sake of convenience. If you want convenience, use JavaScript(Also, I am not advocating for neither JS nor TS. But it just seems the logical fit in this case.)!

For me, the sweet spot between readability and type annotations is JSDoc. I find that it strikes a nice balance between the two. While bloating the code with type annotations can make it less readable, JSDoc, however, allows for a more powerful way of documenting our code by also providing type annotations.

Just sayin'.

Thread Thread
 
kukulaka profile image
Tanya Byrne

because they have to because that's what their job uses?

Collapse
 
alioshr profile image
Aliosh Romano

this is click bait dude =)

Collapse
 
somecallmetim profile image
Tim Mensch

TypeScript is the go-to language for both frontend and backend developers today. Poe's Law is preventing me from being able to tell whether you're actually serious or you're just trolling TypeScript fans.

I mean, you point out that there's more typing...and then duplicate the types in the TSDoc, which isn't necessary. The TypeScript types are vastly superior to the unverified and likely stale JSDoc comments. Also, having real types in your app, in my experience, speeds up development by 2-5x, so any extra actual typing is more than compensated for by the increased development speed.

And types aren't useful? Only if you press the any button too often, which is another of your "downsides." Yeah, it hurts when I do that? Don't do that.

And FlowType...which is used on Facebook projects and practically nowhere else. Where's the DefinitelyTyped equivalent? Pretty much absent.

And unit tests in TypeScript don't need to be hard to use. Instead of having them take a class parameter, have them take an interface that needs exactly the members you need in the function you're testing.

So many others are just reaching. "I hate Microsoft. Sort of." Really? Whatever.

Again, masterful troll, poor actual technical critique. TypeScript gets you to a level of software engineering impossible in JavaScript.

Collapse
 
leob profile image
leob • Edited

Haha:

"whether you're actually serious or you're just trolling TypeScript fans" ...

I'm pretty sure the author is serious, although for a moment I also thought he might be trolling.

Collapse
 
brense profile image
Rense Bakker

Its both, he is serious but also trying to start a flame war at the same time because it helps his statistics. This article is going to be at the top of the listings for a while.

Thread Thread
 
szsz profile image
Sz.

Yeah, and it's kinda sad. I'm very new to dev.to, just test-driving, but I think I'll just skip it (the same way as TikTok), if it continues with this content ballooning strategy (which I don't think it can/would change, actually).

Thread Thread
 
leob profile image
leob

I think the discussions are often fun, and in many cases they're more interesting (and sometimes even higher quality) than the articles proper ... the good thing is that the discussions (almost) always remain respectful and on-topic - kudos to the dev.to moderators!

Thread Thread
 
wiseai profile image
Mahmoud Harmouch • Edited

I think it is always better to post good constructive criticism than to simply ramble on. However, there is always a time and a place for both types of comments. Sometimes, it is helpful to simply vent and get our thoughts and feelings out there, even if they're not perfectly articulated. But, It is better to post well-articulated arguments like what @tqbit did in his comment. Anyways, thanks for contributing to the discussion!

Thread Thread
 
brense profile image
Rense Bakker

Strong disagree there. I have seen very few discussions with opposing views that remained respectful and when the author of the article shows their utter contempt of the people with different views (which is extremely disrespectful in my humble opinion but not against the rules for some reason). If the people in question respond, the dev.to mods ban THEM instead of the author who created the context and is the actual instigator of the disrespectful discourse. Discussions can be fun, but only if one of two scenarios is true: Either they moderate the platform equally and everyone who shows disrespect gets banned, OR you allow the community to moderate itself which means if someone acts like an ***hole, you can tell it to their face. Instead of the current situation where you get muzzled by the dev.to moderator team, while they allow the instigators (trolls) to continue.

Thread Thread
 
brense profile image
Rense Bakker

People DID post constructive criticism with examples that proved some of your points were NOT valid and you responded by putting yourself above them and suggesting they didnt read your article properly. Thats arrogant and disrespectful and you should be banned for it in my humble opinion.

But not to worry though the dev.to team got your back and they will probably ban me instead for calling you out on your behavior. Succesful troll succeeds 👍

Thread Thread
 
wiseai profile image
Mahmoud Harmouch • Edited

People DID post constructive criticism with examples that proved some of your points were NOT valid

I completely understand that. I'm just like you, a human being who is trying to become perfect. And I know that it's not always easy. But I do think that some of the points in the article are still valid. Especially when it comes to using TSDoc to document your TS code, whereas you can use JSDoc with JS and it provides everything that TS has to offer.

suggesting they didnt read your article properly.

That's what it seems like. If not the case, it is OK and I would be responding with the same points written in the article. That's why I suggested reading it. And it is also sad that some people are jumping straight into the comment section without even daring to read the introduction.

I have seen very few discussions with opposing views that remained respectful and when the author of the article shows their utter contempt of the people with different views

Discussions can be fun

Hence my comment:

Sometimes, it is helpful to simply vent and get our thoughts and feelings out there, even if they're not perfectly articulated.

Thread Thread
 
leob profile image
leob • Edited

I think we also shouldn't be too quick and eager to be calling for others to be banned, something with the pot and the kettle ... ;)

Sometimes you just need to let it go, the way I see it is that discussions like these are mainly a bit of fun, even when they get "heated" - let's not take it too seriously and be TOO sensitive, it's not the end of the world.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

More of this, Please. Thank you.

Thread Thread
 
brense profile image
Rense Bakker

Maybe the author should let it go and just not use typescript if it upsets them so much. Instead of going on a dev platform and trying to start a flame war that might get others banned of said platform. 🤷

Thread Thread
 
longebane profile image
Long Dao • Edited

As much as I disagree with author, I think he is perfectly fine writing a controversial article like this. It's an opinion piece what can excite flaming, sure. But it can also be educational for others who don't have a strong inclination towards a side.

Thread Thread
 
idleman profile image
idleman • Edited

It is not a controversial article, more like educational because people don't know most of the stuff he points out. They are like you, refuse to accept the truth. But most points is correct.

If TypeScript provided real type safety, it would enforce every single type at runtime and for the most basic primitives, enforce memory constraints and so on, like Rust/C++.

Thread Thread
 
brense profile image
Rense Bakker

Except theres nothing educational about it, as was already pointed out by several others. The examples are fabricated. In other words: the author is lying in order to provide argumentation for their personal opinion.

Thread Thread
 
idleman profile image
idleman

No, most of the stuff he mention is correct. You just don´t know better because you have been told massive with lies and cannot check it yourself. You probably want to believe it yourself too, making it even harder for you too see the truth.

One of TypeScript largest myth is about it has type safety, which is bs. You can cast anything to anything is TS, can it is by definition not type safe. In C++/Rust you cannot do it, because those language has REAL type safety. If you want to prove TypeScript is type safe, you need prove the "cast" operator do not exist in TypeScript and all objects has memory constraints (= fixed memory size). And this is 100% not the case.

Common kids, this debate is over 40 years old. Types don't make any real difference if you take everything into account. It is time to grow up, really.

You swap development speed for catching simple bugs, that never reach production anyway if you have a good tests (which is required anyway!).

Want development speed: Go JS.
Want types: Go Rust/C++ and compile it to WebAssembly
Want slow development speed and no type safety: Go TypeScript.

That is the hard truth.

Thread Thread
 
brense profile image
Rense Bakker

I think you misunderstood what the word type safety means.

The ability to typecast does not make a language not type safe:

function someFunc(funcParam:string, anotherParam:number){
  // you can rely on funcParam always being a string
  // and anotherParam will always be a number
  return anotherParam as string
  // you can rely on this function always returning a string
}
Enter fullscreen mode Exit fullscreen mode

This is what typesafety means. You do not have to write arbitrary conditions in your code to check whether a function returned what you hoped it would return. Without typesafety the function above would look something like this:

function someFunc(funcParam, anotherParam){
  if(typeof anotherParam !== 'string') return anotherParam.toString()
  return anotherParam
}
Enter fullscreen mode Exit fullscreen mode

And that check is still highly naive what if anotherParam is of a type (like undefined) that does not have a toString() method? Exactly, you get a runtime error.

Also if you think c++ does not have typecasting... youre just plain wrong: typecasting in c++

So come on kids, instead of acting like kids and talking BS about stuff you know nothing about, how about go read up on the things you want to talk about. In the spirit of that, I will admit I know nothing about c++, but that page about typecasting was easily found.

Thread Thread
 
idleman profile image
idleman

You have no clue what you are talking about. I know TypeScript claims to have type safety and I know they do static checks that is obvious wrong, but beside that, no fking type safety at all! They are just wishes, please give me an an object of "type" and you may get an object of "type", say an integer. In C++ and Rust if you say you want some primitive value, 100% of the time you you get it. Real typed languages have CPU constraints and memory constraints. You can simply speaking TRUST an int is an int if the type says it is an int. In TypeScript you cannot DO IT! It is just a wish.

You should not try to teach other people what type safety means, when you clearly does not know even be basics in programming beside some fancy TypeScript stuff that are 99% just adversating talk from the team that sell the product.

I am not against types, but if the language says it is type safe, and a lot of people just repeats the lie when it is simple to provide this is not the case, it is extremely annoying. Sure, I know TS core team know it is not type safe, but they want to sell their product so it is reasonable they continue to spread the lie. But rest of you, what are your excuse?

Thread Thread
 
leob profile image
leob

In my opinion, both Renske and you are overly aggressive in your style of debating ... we don't need to be over-sensitive but "you have no clue what you are talking about" and Renske's "BS" paragraph are examples where you guys resort to needless "ad hominems".

This article really started a flame war, nice for the entertainment if you're into it, but we're not really getting anywhere. My take on TS is, if you think it benefits you then use it, if you think not then don't use it.

Thread Thread
 
idleman profile image
idleman

Yeah, its my mistake. I don't mean to be so aggressive.

Thread Thread
 
leob profile image
leob

No worries :)

Thread Thread
 
brense profile image
Rense Bakker

It was actual BS though. And they continue digging a deeper hole of BS. Tbh their nonsense is so far out there that it's not even worth responding to anymore.

Thread Thread
 
somecallmetim profile image
Tim Mensch • Edited

Yeah, I'm with you there. You were appropriately calling a BS argument BS. That's not an ad hominem.

Saw a video recently about static types and C++ that had a related point: If you're arguing, you're losing.

We're arguing. They have an emotionally based disklike of TypeScript. We will never move the needle with logic.

I mean, above the surgery calls my post a ramble, and accused me of not reading the article. But then he goes on to repeat the same misinformation that I've already debunked. Speaking of not reading what was written.

Let them use inferior tools and celebrate that practice. There's nothing we can say to change their opinion.

The video is long, but it details a guy spending years trying to advocate for C++ in the embedded community, and he was far more patient and strategic than I've ever been--and yet he still failed. It's a good watch.

 
brense profile image
Rense Bakker

The points raised in the article are not correct as was already pointed out by several other commentors. The examples are fabricated and the only substance that remains is the authors personal aversion of Typescript.

I am sorry Typescript isnt working out for you. Nobody will force you to keep using it if you have convinced yourself that Typescript produces more runtime errors than using plain Javascript. Goodluck with that. 👍

 
leob profile image
leob

Yeah actually I had a negative experience, once, with dev.to moderation - I received a one week ban, and my "opponent" as well, while my verbiage was still reasonably polite and moderate, while his was just extremely rude - but we both received exactly the same kind of slap on the wrist (one week ban) ! That did feel unjustified, but oh well, in a case like that you sometimes need to let it go and think "whatever".

Collapse
 
wiseai profile image
Mahmoud Harmouch

And types aren't useful? Only if you press the any button too often, which is another of your "downsides." Yeah, it hurts when I do that? Don't do that.

I didn't do that. The compiler chose the any type, not my fault.

And unit tests in TypeScript don't need to be hard to use. Instead of having them take a class parameter, have them take an interface that needs exactly the members you need in the function you're testing.

It becomes harder when you decide all of a sudden you should change a specific variable type which reflects on the test case.

So many others are just reaching. "I hate Microsoft. Sort of." Really? Whatever.

I mean, what's your decision when you realize that the CEO of the company you are working with shared such an opinion on Linux and open-source in general? Of course against him.

Again, masterful troll, poor actual technical critique. TypeScript gets you to a level of software engineering impossible in JavaScript.

Sorry if you took it that way. I think you will change your mind if you ever considered reading it carefully. But, it is ok if it is not the case.

Thanks for leaving a comment, btw.

Collapse
 
vectorjohn profile image
John Reeves

It becomes harder when you decide all of a sudden you should change a specific variable type which reflects on the test case.

In javascript, in the best possible scenario your unit test then fails and you have to fix the code anyway. More than likely, your test continues to pass and your start getting silent errors at runtime.

Collapse
 
insidewhy profile image
insidewhy • Edited

I didn't do that. The compiler chose the any type, not my fault.

Because you didn't enable strict mode. Which no TypeScript developer I've worked with would fail to do. So I wonder you actually use TypeScript that much.

Collapse
 
seanmay profile image
Sean May

The compiler chose any because you have a var that is declared but not defined, and also not typed. If you don't give either a type or a value to a variable, then it's going to class it as any, so that you can put whatever you want into it, later.

let a = "x";
let b = 5;
let c = a + b; // <-- knows it's a string
Enter fullscreen mode Exit fullscreen mode

100% valid TypeScript.
Solved problem.

Collapse
 
iseiryu profile image
Sergey

when you realize that the CEO of the company you are working with shared such an opinion on Linux and open-source in general

US dropped nuclear bombs on Japan. Japan slaughtered China. Britain colonized the world. I won't even say what Germany did. And yet, those countries are globally respected.

That CEO has been retired for a very long time. Nowadays Microsoft uses Linux to run their own servers and apps.

It's also worth noting that GitHub, VSCode, npm, Azure are also their products. Their representatives also put weight into development of things like OpenTelemetry, CNCF (cloud native computing foundation), WASI and many other important things.

Collapse
 
vectorjohn profile image
John Reeves • Edited

The first example in "why use typescript" is not an example of Typescript not catching an error. It's an example of Typescript working exactly right. You said "TypeScript doesn't recognize the type mismatch and type-checks the code successfully" - there is no type mismatch. You literally said the function push accepts arrays that contain numbers and strings. So pushing a number into it is perfectly fine. Arrays that contain mixed types is allowed, how else would you type something like that?

If you want to do what it looks like you _meant _to write, you would say:
function push(arr: Array<number> | Array<string>) ...
or if you didn't want to look like you read the TS hello world yesterday:
const push = (arr: number[] | string[]) ...

In other words a function that accepts arrays of numbers or arrays of strings. Then it would notice that you didn't check the type in the arr.push call. Perfect.

Also your Rectangle class example is misleading. You say you're just comparing Typescript to JSDoc but they are two very different programs. Your JSDoc version doesn't allow strings and you're comparing it to a Typescript version that does allow strings. You also wrote it in a very naive way that should really be cleaned up. If you want to (very weirdly) allow string | number everywhere, make that a type. type RectAttr = string | number, then use that everywhere. Bam, cleaner and more informative than the JS one. But since your JS version just completely blindly accepts any input and happily coerces it to number at runtime, it's not really showing the strengths you think it is. It sucks, frankly. What good is a program that runs without complaint when I write (new Rectangle({})).calcArea()? That shouldn't get past anything but it does.

As others have suggested, this sounds like just an error of not having any experience using Typescript. This isn't even advanced stuff, that's the basics. I recommend you take some time and learn Typescript, once you actually get past hello world, it becomes apparent that it's very powerful.

There may be reasons to have misgivings about Typescript, possibly. But they'd have to be reasons that vanilla JS is better, and it simply isn't. This is very close to not even being a matter of opinion anymore. Even a mediocre type system (and TS is an excellent one) is better than none.

Collapse
 
wiseai profile image
Mahmoud Harmouch • Edited

or if you didn't want to look like you read the TS hello world yesterday:

Arrow functions are now a higher standard, ok.

As others have suggested, this sounds like just an error of not having any experience using Typescript. This isn't even advanced stuff, that's the basics. I recommend you take some time and learn Typescript, once you actually get past hello world, it becomes apparent that it's very powerful.

Alrighty. We have a TypeScript Chad over here. I have put this simple example intentionally just to show how people are ridiculously good at throwing insults, rather than pointing out how the compiler can sometimes act drunk. Since you have some TypeScript experience, I suppose you worked with enums before. So, could you please tell me what's wrong with the following enum?

enum ChatStatus {
  Online,
  Offline,
}

let chatStatus: ChatStatus;

chatStatus = 999999;

console.log(chatStatus)
Enter fullscreen mode Exit fullscreen mode

And guess what? OMG, The strict mode is enabled! Could you please tell me what is the point of enums if it doesn't limit the values to just 0 and 1?

JS is better, and it simply isn't.

It would be great If you could prove that TS is better than JS.

Here you go another example when the compiler assigning the type to any which is a valuable type to have, I guess?

interface Foo {
  objects: { id: number; }[];
}

class TestFoo {
  foo: Foo | null;

  doSomething(ids: {}) {
    if (!this.foo) return;

    for (let index in this.foo.objects) {
      const object = this.foo.objects[index];
      const objId = object.id();

      if (!ids[objId]) return;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Result:

any type

That said, I doubt that TypeScript is worth learning like at all. It trips you up a lot more than just writing vanilla JavaScript. In my experience, the benefits of using TypeScript are not worth the trouble it causes.

Have a good day.

Edit: I am not going to list every single flaw / common pitfall in TypeScript. You get the point. However, One fact still stands:

TS is NOT better than JS.

Collapse
 
vectorjohn profile image
John Reeves • Edited

With the enums, well, congrats you found a skeleton in the closet of the language, a bad design choice made early on that they are trying to fix but are kind of stuck with. I'm sure Javascript has none of those. Enums just shouldn't be used in my opinion because they are not actually enums. As designed, they're meant to represent bit flags unless you use string enums. Instead, one should just use unions or one of the many other more enum-like things.
Keep in mind, Typescript isn't C# or Java, you have to actually learn it not just assume all the constructs work the same way.
Anyway, on to your next example. That doesn't compile for me. When I write const object = this.foo.objects[index] it fails with "object has implicit type any". As expected. This is from the noImplicitAny flag, which is also enabled by simply using strict mode as many of the comments in this thread have told you repeatedly is the standard if you want type safety.
The any type only exists to babysit old bad Javascript code and idioms. It shouldn't be used explicitly nor should you allow things to implicitly become any, which is why the noImplicitAny flag exists.

It trips you up a lot more than just writing vanilla JavaScript.

This is an assertion made without experience. There is no way this is true, javascript has libraries of books and exobytes of websites dedicated to teaching people how to avoid all the pitfalls and rough edges of Javascript, not use certain dangerous language features, and on and on. It trips up beginners and newcomers to the language by acting differently than expected (especially with people who think it's similar to the language it is named after). The language is full of surprises and weird behavior, it's practically a meme. Typescript takes many of those lessons learned and enforces them with a compiler which is eons better than a human at actually finding errors.

You're taking these few odd edge cases that many people never even noticed after using Typescript for years and saying because of this odd edge case the language is bad and not useful. This is absolutely hilarious and ironic coming from someone advocating for Javascript.

TS is significantly better than Javascript and to me, that's an objective fact. There may be some reasons to like JS still, from time to time, but usually not. Development time is faster in Typescript, quality is better, readability (the actual most important part of code) is better. All the complaints you may have about Typescript apply just as well to Javascript, but none of the benefits of Typescript apply to Javascript. You find weird edge cases that don't come up in practice and ignore the 99% of the time where the language does exactly what you expect.

As a professional software developer with 20 years experience and most of those using Javascript, I would never go willingly back to Javascript and actively promote upgrading Javascript (or Java for that matter) code into Typescript where possible. I also recommend against hiring anybody who would argue things like Javascript being preferable. Typescript is just so much easier to use and better on every level.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

A bad design choice made early on that they are trying to fix but are kind of stuck with.

Ah, I see.

Enums just shouldn't be used in my opinion because they are not actually enums.

That's what I have learned from this example.

Instead, one should just use unions or one of the many other more enum-like things.

I see.

which is why the noImplicitAny flag exists.

Got it!

Keep in mind, Typescript isn't C# or Java, you have to actually learn it not just assume all the constructs work the same way.

I am not sure if I am the only one who doesn't understand the motivation behind TypeScript, but I will give it a shot. First of all, C#, also created by Microsoft, is a strongly typed language that can be used to create web applications. However, JavaScript is a dynamically typed language that can be used to create websites. So, my question is, what is the place for TypeScript in this equation? Don't get me wrong. I am not saying that innovation is a bad thing. What I meant to say is that it looks like TypeScript doesn't seem to me fulfilling a practical use case. However, it is highly likely to be acting like a bridge between C# and JavaScript, allowing developers to use familiar syntaxes while leveraging the power of dynamic languages like JavaScript. In this case, that would make sense.

The language is full of surprises and weird behavior, it's practically a meme.

Exactly. Hahahaha.

Typescript takes many of those lessons learned and enforces them with a compiler which is eons better than a human at actually finding errors.

Cool.

You're taking these few odd edge cases that many people never even noticed after using Typescript for years and saying because of this odd edge case the language is bad and not useful.

Alright!

As a professional software developer with 20 years experience

Now, we are talking.

I also recommend against hiring anybody who would argue things like Javascript being preferable.

Lol. Really? But, I think that advocating for either JS or TS is the same thing. Since you will end up with JS code in both cases. However, I think that C# is a better option than TS in my opinion.

Typescript is just so much easier to use and better on every level.

Will see.

Collapse
 
brense profile image
Rense Bakker

Your enum example has nothing to do with enums.

You are reassigning the chatStatus variable, it's not longer an enum. Its the same as complaining your array is no longer an array when you reassign it:

let someArray = [1, 2, 3]
someArray = 'now its not an array duh'
someArray = 42
someArray = undefined
// what is your point?
Enter fullscreen mode Exit fullscreen mode

Obviously if you reassign a variable its not going to complain, since you are reassigning it... Reassignment is not a typescript thing, its a javascript thing. Thats how javascript works and since typescript is a superset of javascript, its also how typescript works.

This DOES throw an error:

enum ChatStatus {
  Online,
  Offline,
}

const chatStatus: ChatStatus = 999999
Enter fullscreen mode Exit fullscreen mode

This would ALSO throw an error:

enum ChatStatus {
  Online,
  Offline,
}

type User = {
  chatStatus: ChatStatus
}

const someObject: User = { chatStatus: ChatStatus.Offline }
someObject.chatStatus = 999999
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
wiseai profile image
Mahmoud Harmouch • Edited

Your comment shows the lack of understanding of what is the point of enums like at all. Besides readability, enums are used to limit the values in a certain range. In Java for example, you can't do this because 999999 is a value outside the enum range [0 for Online, 1 for Offline]. Moreover, enums are mainly used in facade design pattern.

Back to your rambling, you can't assign, however, a value of type string to an already declared number variable:

Image description

In the case of enums, the compiler should complain that 999999 is outside of [0, 1].

That's the whole point.

Have a nice day/evening.

Edit: I think TS is following the same C# philosophy where it can accept any value that a number can. That's why 999999 doesn't throw any exceptions. Alrighty.

Thread Thread
 
brense profile image
Rense Bakker • Edited

Your point is that you want typescript to work exactly like C# Have you considered just using C# then?

In any case, congrats, you found one quirk in Typescript. Enums are implemented kinda shitty, according to you that invalidates the whole concept of Typescript... Good for you. Luckily most other developers are capable of being a little less biased. If you need to have typesafe enums in Typescript, you can try to not be an obnoxious hater and use unions like everybody else:

type ChatStatus = 'Online' | 'Offline'
let chatStatus:ChatStatus = 'Online'
chatStatus = 9999
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
wiseai profile image
Mahmoud Harmouch

Typescript, you can try to not be an obnoxious hater and use unions like everybody else:

Yup, that's what most folks suggested.

Thread Thread
 
brense profile image
Rense Bakker

You could have done somesthing constructive and wrote an article about why not to use enums in Typescript, explain to people its better to use unions. You would get less, but much better responses and people would actually learn something. Or if you have a suggestion on how Typescript SHOULD implement enums, you can make a pull request on their repo: github.com/microsoft/TypeScript or create an issue: github.com/microsoft/TypeScript/is... they are pretty open for constructive feedback from users.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

You could have done somesthing constructive and wrote an article about why not to use enums in Typescript, explain to people its better to use unions.

Noted.

Or if you have a suggestion on how Typescript SHOULD implement enums, you can make a pull request on their repo: github.com/microsoft/TypeScript or create an issue: github.com/microsoft/TypeScript/is... they are pretty open for constructive feedback from users.

I am afraid to contribute to that repo cause, by now, every engineer at MS thinks I am mentally disabled or something along this line. LMAO.

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited
For example, suppose you decide to use Typescript for your project. You may think this language will be easier to maintain in the long run as it is more type-safe than other languages. However, halfway through the project, you realize that a different technology stack would be better suited for your particular project. You now have to go back and refactor all of your existing code from Typescript into the new technology stack, which can take considerably longer than if you had chosen the correct language from the beginning. As a result, you find yourself weighed down by tech debt that could have been easily avoided with proper planning at the start of your project.

Yeah... I mean... Abso-freakin-lutely!

Just the same that happens when you start a project with any language and platform.

The cost of redoing that is related to the team's expertise on the old and new language/platform/framework as well as the LoC, complexity, maturity (of both the project and the team) and quite a few points more.

Still I can't see why TS is set here as example, it's honestly worse with vanilla JS.

On the other hand that's one of our jobs (for us Tech Leads and software Architects) to do the right tech choices based in different points we need to weight and tackle before even a developer writes a LoC.

I am a big advocate for JSDoc, not as a replacement for TS but because the reality is that there are way more vanilla JS projects than TS + Flow + whatever new type-system-for-JS combined, and using JSDoc along TS Pragma makes it way easier to migrate the project to TS later on.

On small to middle projects, JSDoc may suffice with the condition that you set some automatic checks to ensure JSDoc is not only added to new functions but maintained when refactoring/modifying existing ones.

On middle to large projects TS is the choice. Flow is nice and so but we're not a research institute (at least in any company I worked in), that's the real market and the decisions should be backed; TS has a large community and maturity thus it's the option (like it or not).

Last but not least I won't let THIS kind of code to be merged into develop. You know? This code that's complex for the complexity, not splitted enough, bunched with arbitrary stuff... A.K.A. "overengineering", bad practices, "look how complex this looks, gimme a rise" and so on and so forth.

This just depends on the people doing the CR and just like with management, PO, DM or any other responsibility job position... You can get either lucky or burned depending on who's sitting on those chairs, and that my friend is not TS's fault.

But if any reader got the stars aligned in a good project and still doesn't like what he's doing, then you're either burned down or you lack the required skills for the job you're doing, and the solution for both is to find a new job.

Hope it helps somehow,

Cheers!

Collapse
 
wiseai profile image
Mahmoud Harmouch

I appreciate your feedback on this matter. I am in agreement with many of your opinions. However, the following could be a valid argument, but not a strong one. One could argue that reformatting code from JavaScript to python or any dynamically typed language is much simpler than reformatting code from typescript to python. This is because when refactoring from JavaScript to python, you don't have to worry about removing the types that were present in the typescript code.

Refactoring from typescript to python however requires more work as you have to manually remove all the types that have been declared in the source code. This can be a time consuming process and may lead to errors if not done correctly.

Thank you for responding. I am a big a fan of your work/opinions! Let's keep fighting!

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Hi Mahmoud,
Thank you for your answer!

Let me tear this down a bit.
While that could be true in certain situations, it's not usually the real experience.

First of all, there are almost no reasons to translate "literally" from JS to Python.
Reasons:

  • Python doesn't work for frontend (you'll need to add JS inside Python anyway and/or use a template engine like Jinja), if you're about to do SSR it's better to use Next JS or similar straightforward (good for horizontal scalability, finding devs for the project, UX and so on).
  • Node is -usually- faster than Python for backend purposes, way better for availability and you'll end up adding a Node JS gateway at least so why add a new language to the equation? it will only harm your ability to find new devs.
  • If you're about to add a new language it will probably be Java, C# or similar, due to the ecosystem around them which can add benefits at the top of what JS or Python can offer.
  • If it were a task for python such ML, NN... you'd already have coded it in python instead.
  • If you need Python (or any other language) for any reason to tackle down a critical building block in your APP it will probably be a webservice/endpoint and not replacing the others that already work great.

On the other hand, it's not a matter of "I have to remove the types manually" as something that bothers you.
Having the types brings you the possibility to slowly but surely write similar functions for the necessary use-cases without the frightening errors in runtime that the QA will point out few minutes after the merge of your PR (or at least way less than without having type hints).

On the other hand, Python does have type hints that work in dev time (just like TS) thanks to IDE implementations and are a nice to have as well.

So, for this given TS function:

const sayHello = (name: string) => `Hello ${name}`;
Enter fullscreen mode Exit fullscreen mode

you will probably write this in Python:

def sayHello(name: str) -> str:
    return 'Hello ' + name
Enter fullscreen mode Exit fullscreen mode

and the equivalent in JS would be

const sayHello = (name) => `Hello ${name}`;

// or 

const sayHello = (/** @type {string} */ name) => `Hello ${name}`;

// or

/**
 * Returns hello {name}
 * @param {string} name 
 * @returns {string}
 */
const sayHello = (name) => `Hello ${name}`;
Enter fullscreen mode Exit fullscreen mode

Depending on the project (to be honest, it's usually the first use-case 😂)

If I was to say something negative around TS is that it sure takes more time to having things done than JS at the beginning and maybe compile transpile times can be itchy, specially if you have a low-spec computer (I'm so used to transpile JS using babel, webpack, Parcel... that few seconds are not doing the difference at all) and of course that the learning curve is higher, but assuming you got the basics on CS you already checked C/C++, Java and many other languages that are for sure more complex in depth than JS/TS hence... idk, it may be just a matter of point of view and self experience 😁

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

Got it. However, I am afraid to ask about a python version of the bubble sort written in TS. LOL.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

I'm not much into python tbh but here's a try:

def bubbleSort(arr: Array[int]) -> Array[int]:
    n = len(arr)

    for i in range(n-1):
        for j in range(0, n-i-1):
             if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
Enter fullscreen mode Exit fullscreen mode

some Py master may point out something wrong idk.

On the other hand you need to be honest. You put over-complexity on purpose to the bubble sort above just to stress your points to an infinite level, and... c'mon man, you know that!😂

This can be done much simpler:

const bubbleSort = (arr: number[]): number[] => {
  const len = arr.length;

  for (let i = 0; i < len; i++) 
    for (let j = 0; j < len; j++) 
      if (arr[j] > arr[j + 1])
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];

  return arr;
};
Enter fullscreen mode Exit fullscreen mode

And it will infer the types accordingly.

Those lessThan types are set there for no reason, a comparison statement
(X > Y, X < Y etc) is always a boolean context (it will always evaluate to true || false).

Around the type checks.... Even Java doesn't check types in runtime (it is the compiler) so of course if you want to have them in runtime, that's a totally different story.

It may be a confusion between type hints or type checks in dev time (something implicit on TS, Java, C# and many other languages) and type checks at runtime (something you need to code yourself in any language as far as I can remember).

Thread Thread
 
vectorjohn profile image
John Reeves

I don't know if you noticed this, but his bubbleSort example was not a run time sort. It was such an unrealistic convoluted example, it was a toy like an obfuscated C contest as others have said. So the lessThan etc types were actually necessary.

His example would make a new type (not a sorted list) that only allows sorted lists as values. Which means it's only for array literals. I.e. you can make a type like type SortedArray and then use it like const x: SortedArray = [1,5,2] (which would be an error because 1, 5, 2 is not sorted).

As mentioned, not a useful or reasonable example, it's exactly like using obfuscated C code to say C is confusing. Your example actually shows what a reasonable bubbleSort would look like in Typescript, which as you note looks almost identical to JS, but isn't doing the same thing.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

Kudos on that John, I honestly didn't even tried to understand everything 🤷🏻‍♀️😂

That being said, I believe that most code snippets I saw online with half this complexity are blending concepts.

One thing is to know that a function argument should be a number and a completely different thing is to ensure the function does what it should using types. We've unit tests for that and they work way better IRL.

If we consider that TS types are touring complete you can do things like those, even you shouldn't and neither it is its purpose.

But maybe I'm wrong, or getting older or idk 😂

Collapse
 
lbodwell profile image
Luke Bodwell

Ok? The same could be said for migrating any other strongly-typed language to a dynamically-typed one. The reverse is also true though. Migrating from TS to another strongly-typed language like Java or C# would be much easier than migrating from JS. As others have pointed out, you seem to have a personal vendetta against TS for some reason and don't have much in the way of actual reasoning for why it's worse than JS, other than niche "what-if" scenarios.

Collapse
 
vectorjohn profile image
John Reeves

Refactoring from Typescript to Python (for whatever would drive a person to do such a thing) is exactly as easy as going from Javascript to Python. You just compile the code. Bam, javascript. Since Typescript doesn't touch the structure of your code, the output will be exactly the same as manually typed Javascript.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

hahahaha didn't even thank about this option. Good one!

Collapse
 
insidewhy profile image
insidewhy

Python has type annotations and pluggable type systems. I like to use these. Therefore refactoring to the type of python I would write would be easier. Then again, if I was refactoring to a dynamic language I could just strip the types via a Babel transform.

 
wiseai profile image
Mahmoud Harmouch

OMG! I couldn't agree more! It's so refreshing to see somebody with level-headed thinking in this day and age. We need more people like you to help set the world back on track. Thank you for speaking up and showing true sanity!

Thread Thread
 
olddutchcap profile image
Onorio Catenacci

"There are several frameworks that are objectively better than React" (emphasis mine).

I don't think you understand the meaning of the word "objectively". I can't think of many things in software development that are objectively better than other things.

Collapse
 
tqbit profile image
tq-bit • Edited

First off, you've obviously dedicated a lot of time and research into this article. I found several very valid and well-thought points, some which I do not agree with and a few that I find simply incorrect (= could not cross-verify anywhere).

TL:DR - I have added a few counter arguments for each of the points of this post, all of which are very subjective. I love JSDoc, especially in environments that do not support TS. Some of your points, in my eyes, might be a bit misleading to devs getting started with the language. You're invited to disagree with each of them, hence the tone.

1. The Learning Curve.

As you state, using TS or not heavily depends on the use case. Given you're working on an enterprise-grade project with several developers, comparing the cost of learning against the cost of later maintenance, I find this no valid argument against Typescript.

Quite the opposite - since it's hard to learn, it's a valuable asset for your portfolio. Learning TS increases your net worth and distinguishes you from other developers.

2. Strict Type Checking System.

The example you provide is literally a type-only bubble sort in TS. I do not find it to be a practical example of static type checks. Applying this principle to anything but snippets feels like writing the whole codebase in a @types directory.

I agree with your statement that complex types are, well, complex. That's why they're being used. Compared to languages like Rust or Java, you do not have to type your whole project. If types are too complex, you're free to leave them out.

3. Verbosity And Lack of Readability.

True, large TS codebases are a mess. Just from my experience, it's not the types per se that cause havoc, but the way they're named and maintained. If you and your co-devs handle them properly and prevent them from rotting, this problem can largely be circumvented.

Regarding one of your alternative solutions: In my eyes, JSDoc is more verbose compared to TS. You can see it in your own example - in many cases properly named variables can easily replace JSDoc comments.

4. Lack Of Intuitive Syntax

See point 1.

5. Lack of Compatibility.

The example you describe is not a problem with the language. Why should I ditch the language if the environment does not support it? That feels like saying 'I ditch Python because it does not run in my browser console' in 2015. This problem led to a great innovation called Pyscript.

6. Low Productivity.

Typescript can be slow and cumbersome, especially compared to more streamlined languages like JavaScript or Python.

Frankly, sometimes I have the feeling I only write types for the compiler's sake. But writing types, enums and interfaces forces me to think through by data structures and optimise on the go. And I would always choose taking weeks longer for the initial release than spending months patching up my mess.

When you are trying to rapidly prototype something during a Hackathon, the last thing you want is to deal with the extra overhead of Typescript.

I do want it because I'll spend only the weekend writing on the code. And I'll have forgotten most of the data structures in the time between. Because I am lazy and do not document a lot (sometimes ChatGPT does that for me), I'm happy seeing my previous thoughts neatly formatted as interfaces waiting for me to come back.

All of my previous Hackathon submissions, after learning the language, are written at least partially in TS. One even won me a grand prize. And I'm happy for the static types, because now I can keep developing on it without reviewing the whole codebase.

Using Javascript is great because of the short time-to-market, but in my eyes, it's largely outweighed by maintenance costs for enterprise grade apps.

7. False Promises.

Also, I'm not too fond of TypeScript because it's a language that tries to sell you the idea of solving all JavaScript problems

If this is true, I have a misconception of the language. Is this your personal opinion or has this been stated by one of the core development team? If so, can you please provide a source for this statement?

For me TS is pretty much this:

The goal of TypeScript is to be a static typechecker for JavaScript programs - in other words, a tool that runs before your code runs (static) and ensures that the types of the program are correct (typechecked).

Source: typescriptlang.org/docs/handbook/i... , second paragraph, last sentence.

8. Lack of Flexibility.

See points 2, 6 and 7

If you're serious about becoming a great developer, you should not settle for a language that limits your creativity and hides the true power of the language.

I don't think TS limits my creativity. All types are optional, nothing prevents me from typing everything with any. But I find it more elegant and more responsible towards my customers to write robust code. With great power comes great responsibility, after all.

9. Giant Corporation Abuse.

Yes and no.

If you don't know yet, Microsoft has a long history of being an anti-open source and anti-Linux.

Fortunately, Microsoft is not solely run by Steve Ballmer. Of course they used to doom Open Source, until they figured how to capitalise on it. And now, there's software like this:

  • WSL (Windows Subsystem for Linux)
  • .NET Support for Linux
  • VSCodium (OS Version of VSCode)

And to provide a more recent opinion on Windows <-> Linux: cloudblogs.microsoft.com/windowsse...

10. Clever Devs Abuse.

This happens in Javascript too & does not really count as a reason to ditch the language

11. Not A JS Superset.

I am unsure how to respond to this statement and the example you provide properly. In general, you're not wrong. Since TS uses static types, types must be known at compile time. This also goes for your example. Yet as stated in point 8, I see no problem in this, but an opportunity to make my code more robust:

type Foo = { bar?: number }

const foo: Foo = {}
foo.bar = 42
Enter fullscreen mode Exit fullscreen mode

12. Slower Compile Time + 13. Additional Transpilation Step

True, that's the price you pay.

14. Lack of Performance.

Usually, you do not ship TS code to production.

Performance can indeed become a problem during development when using TS in Node.js using ts-node or nodemon. In the frontend, Vite does a good job at solving performance issues.

15. Writing Unit Tests.

I find it even easier because all my types are already declared and, if I did a good job, count for tests and the software.

For example, if I need to change a single property of an object used in a test, I would have to go back and modify the type definition and the test code itself.

And where's the problem? I would want my co-dev to document a change like this somewhere.

I still remember an upgrade from formidable v2 -> v3, where a single property name changed and I spent a whole week figuring this out (in a JS codebase) because the app would keep crashing. Okay, I haven't read the breaking changes in the log, but I was still quite upset about such a minor change making such a huge impact.

16. Types Are Not That Useful.

See points 1-15

17. Heavier Tech Debt.

Typescript can be a major issue when a project's scope, tech stack, or architecture changes halfway through the process

Sure there are madman PMs changing the architecture halfway through the project. But that's not technical debt, it's poor planning.

Also:

You now have to go back and refactor all of your existing code from Typescript into the new technology stack, which can take considerably longer than if you had chosen the correct language from the beginning.

Boy am I glad the concept of static typing is language agnostic.

Collapse
 
wiseai profile image
Mahmoud Harmouch • Edited

First off, you've obviously dedicated a lot of time and research into this article. I found several very valid and well-thought points, some which I do not agree with and a few that I find simply incorrect (= could not cross-verify anywhere).

Thank you so much for your kind words! Oh thanks! I'm glad you appreciated all the work that went into this article. It's true that a lot of research and time went into it, and I'm pleased to hear that it was worth it. I'm glad that it resonated with you. Thank you for taking the time to read it.

I love JSDoc, especially in environments that do not support TS.

This!

You're invited to disagree with each of them, hence the tone.

Let's do this!

1. The Learning Curve.

Quite the opposite - since it's hard to learn, it's a valuable asset for your portfolio. Learning TS increases your net worth and distinguishes you from other developers.

Of course, I mean if you want to pay me xxx$ , I can learn whatever the heck you wanted. That's not the point. As stated in the article, the main point is:

In short, the learning curve associated with Typescript can be quite steep and require significant time and effort to master.

2. Strict Type Checking System.

Applying this principle to anything but snippets feels like writing the whole codebase in a @types directory.

Agree with this.

3. Verbosity And Lack of Readability.

True, large TS codebases are a mess.

This!

If you and your co-devs handle them properly and prevent them from rotting, this problem can largely be circumvented.

The same argument can be made for JS. If you and your co-developers follow the best practices in JS, this problem can largely be circumvented. By following best practices, you can ensure that everyone on your team is on the same page, which makes it easier to avoid errors and manage code changes.

In my eyes, JSDoc is more verbose compared to TS.

But in the case of using TSDoc with TS, you will end up with the same verbosity.

in many cases properly named variables can easily replace JSDoc comments.

This opens up a whole new debate: Proper Naming Convention Vs Code Documentation. But, Agree with you on this point.

5. Lack of Compatibility.

You points are valid over here. But, sometimes it can cause headaches. It is my fault that I didn't provide a reproducible example cause it's was too complicated and I don't have the rights to share it.

6. Low Productivity.

Frankly, sometimes I have the feeling I only write types for the compiler's sake.

This!

And I would always choose taking weeks longer for the initial release than spending months patching up my mess.

So, it is clear that it will lower your productivity, ok.

All of my previous Hackathon submissions, after learning the language, are written at least partially in TS. One even won me a grand prize. And I'm happy for the static types, because now I can keep developing on it without reviewing the whole codebase.

I think your experience is great and I'm happy you had success with using TypeScript. However, I disagree with using it in a time-constrained environment such as a one-day hackathon. The learning curve for TypeScript is quite steep and there's not enough time to came up with a prototype to take full advantage of its benefits.

7. False Promises.

If this is true, I have a misconception of the language. Is this your personal opinion or has this been stated by one of the core development team? If so, can you please provide a source for this statement?

If it doesn't solve JavaScript problems, then what is the point of inventing this language? I would say, it is not 100% valid, yet still a speculative argument.

The goal of TypeScript is to be a static typechecker for JavaScript programs.

The absence of a static type checker is a problem in JS, isn't it?

14. Lack of Performance.

Performance can indeed become a problem during development when using TS in Node.js using ts-node or nodemon.

This!

I see your points, and I understand where you're coming from. However, I would argue that you would still resort to TS/JSDoc anyway to document your TS code. Have a look at the core TS code and let me know. This begs the question: why use TypeScript in the first place? Know what I am saying?

Collapse
 
tqbit profile image
tq-bit

I apologize should I have mislead you, but my words were not meant to be kind, but critital. Yes, you did a lot of research and I appreciate the article. That doesn't mean that I agree with everything.

However, I would argue that you would still resort to TS/JSDoc anyway to document your TS code

What gave you this idea?

The repository you linked includes a ts declaration file for interfaces. In this case, JSDoc is used to provide additional information inside IDEs or text editors. Try and type the following in your IDE:

[].find
Enter fullscreen mode Exit fullscreen mode

Hover over find. You'll see the JSDoc comments are equal to the text content. Also, the declaration file is for vanilla ES6 Javascript features and tbf I'm happy for every piece of documentation I can get.

There are more examples. Projects like Deno also ship fully commented interface libraries because they're very useful to develop with:

github.com/denoland/deno/blob/421e...

why use TypeScript in the first place?

There are two answers, one for this case and a generic one.

For a code library like this, I am happy when people do proper documentation. The documentation happens to be part of the code. And it integrates well into my IDE, too. Sounds good.

For all other cases

  • Using JSDoc provides me the neat help text you see when hovering methods. It's also useful to automatically generate static docs which are always equal to the code suggestions in my codebase
  • Using Typescript provides code suggestions & helps me make my project more robust. There is a VSCode setting that includes static type checks for JS + JSDoc, but since the compilation step is missing, I do not have the chance to enforce this rule.

The latter is, again, especially important when working in teams. And I don't have to use JSDoc to provide these small popups in the IDE, normal comments are perfectly sufficient.

By now, I see a lot of projects that use the monorepos style written in TS. Because while not essential, it helps to prevent code rigidity. Below are examples for three robust and famous frameworks with a huge codebase and many team members:

Thread Thread
 
wiseai profile image
Mahmoud Harmouch • Edited

I apologize should I have mislead you, but my words were not meant to be kind, but critital. Yes, you did a lot of research and I appreciate the article. That doesn't mean that I agree with everything.

I meant not in an insulting way. Criticism is always welcome.

JSDoc is used to provide additional information inside IDEs or text editors.
Using Typescript provides code suggestions & helps me make my project more robust.
Using JSDoc provides me the neat help text you see when hovering methods.

That's the whole point. Why using TS in the first place and TSDoc with TS when you can use JSDoc for type-checking, documentation, and code suggestions in JS?

Thread Thread
 
tqbit profile image
tq-bit • Edited

I think you're answering this question with a few of your article's points.

  • TS enforces strict types and invites developers from other statically typed, OOP - based languages, like Java and C#, to participate in projects. With the static types they already know and the flexibility of Javascript's core features

  • TS is actually (mainly) intuitive syntax (once you get used to it).

  • Compared to Javascript, TS reduces tech debt on the short & long run. It makes mono-repositories easier to maintain & libraries and modules public APIs less prone to errors. Because you have a compiler to convince that your logic is sound, with all pros and cons that brings.

Now you could argue: Well, all of this goes for JSDoc, too, doesn't it?

Yes and no. Because

  • JSDoc enforces no strict types. There is Javadoc, but I've seen it used very rarely in the wild, while Java Types are everywhere

  • JSDoc is verbose and not part of the code, but a textual extension. I don't find typing out function arguments very intuitive. Not now, probably not ever. I keep forgetting how to do a proper @typedef every other time and I cannot declare complex types. Also, I find generics in JSDoc rather ugly.

  • (maybe the most important part): JSDoc has no compiler. You can type your whole codebase with JSDoc without any other benefit but the comments in your IDE.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch • Edited

TS enforces strict types and invites developers from other statically typed, OOP - based languages, like Java and C#, to participate in projects. With the static types they already know and the flexibility of Javascript's core features

See. You are providing already existing statically typed languages. Why bother creating a new one? Oh, I forget, it is just another standard.


xkcd.com/927

JavaScript has become one of the most popular programming languages in the world because it gives us the freedom to write code without being constrained by static types. People seem to forget that.

TS is actually (mainly) intuitive syntax (once you get used to it).

For me, it is. However, I think it's really hard for developers who are just starting out using the language. There are SO many questions and common pitfalls that can trip them up. It's scary!

JSDoc enforces no strict types.

In VSCode, just enable it in file > preferences > settings > search for "checkjs"

And Bam! You got semantic checking enabled (kind of static typing).

Image description

Image description

JSDoc is verbose

How about using TSDoc with TS code?

(maybe the most important part): JSDoc has no compiler. You can type your whole codebase with JSDoc without any other benefit but the comments in your IDE.

What? Are we talking about semantic checking NOT a benefit?

Thread Thread
 
smolinari profile image
Scott Molinari

JavaScript has become one of the most popular programming languages in the world because it gives us the freedom to write code without being constrained by static types. People seem to forget that.

This is SO wrong. JavaScript is as ubiquitous as it is because of browsers and the Internet. Had JavaScript not been the language used to make HTML interactive and there would be some other language, then we'd all be using that more than likely. The popularity of JavaScript today has NOTHING to do with what JavaScript is as a language in the end. I'd also add that JavaScript as a programming language only really became significant in 2010, when the first Node version came out, allowing JavaScript to be used for both frontend and backend applications. It doesn't matter either. The point being, I think we can agree, JavaScript is the #1 web application language right now.

Now, my correction also doesn't make your point moot. JavaScript can and does give us the freedom to write code without static types. However, once a code base gets to a certain size, this freedom becomes a very common footgun and that is why TypeScript became even a thing and why it is growing fast. Because teams of developers need type safety.

I'm not going to go into your litany of reasons not to use TypeScript. I'll say for sure, you are swimming against the stream that is gaining in strength. Instead of complaining with a list of shaky reasons to dislike TypeScript, put your energy into supporting making the language better, because, JavaScript's and TypeScript's ubiquity isn't going to stop any time soon. It is all here to stay. And if I were you, I'd want to make waves by making the language better, instead of looking like the one whiny fish who thinks the stream is going in the wrong direction and ending up bumping heads with the other fish going that same direction. It's counterproductive for us all.

Scott

Collapse
 
tqbit profile image
tq-bit • Edited

See. You are providing already existing statically typed languages. Why bother creating a new one?

I think you're trying to compare apples to pears. Have you ever tried to write a React app using C#?

Regarding 'Why bother creating a new one?'. Because competition is good for innovation. I don't see competing standards as a bad thing. Because they compete to be the best, hence they keep improving. And from my minor perspective, TS is superior to JSDoc in terms of static type checking in every way.

JavaScript has become one of the most popular programming languages in the world because it gives us the freedom to write code without being constrained by static types.

Types in Typescript are optional

However, I think it's really hard for developers who are just starting out using the language.

Can you verify this? I found it hard because I never worked with static types before. And I would argue that the hardest part is to learn the syntax - which is true for all other languages. I think it's really hard for developers who are just starting using ANY language.

JSDoc enforces no strict types.

In VSCode, just enable it in file > preferences > settings > search for "checkjs"

That's no strict type checking because there's no compiler, just the Typescript language server. (Yes, even JSDoc uses Typescript under the hood, hooray for standards.)

JSDoc is verbose

How about using TSDoc with TS code?

Looks pretty verbose too. Perhaps I should have formulated: 'JSDoc to be looks more verbose than Typescript based on the lines of text added to a particular file'.

What? Are we talking about semantic checking NOT a benefit?

I'm not sure how you got that idea tbf. I stated that JSDoc has no compiler and TS does.

With 'You can type your whole codebase with JSDoc without any other benefit but the comments in your IDE.', I meant:

  • You can ship incorrectly typed code (could have errors, could have none)
  • JSDoc will not stop you, because there is no compilation step involved.

If there is an error due to wrong type expectations, you might not even notice it in the application itself. I love Javascript's anarchistic approach to dynamic types, it's what opened the gate to programming to me. At the same time, I've seen horrible crimes being comitted using Vanilla JS - Syntax in non-strict mode.

Imagine you have a shop system. A customer orders a t-shirt and a jacket. Your junior dev has presented a logic to calculate shipping fee based on the total amount of items.

const shirt = {
  name: "Shirt", 
  price: "19.99", 
  currency: "EUR", 
  qty: "1"
}

const jacket = {
  name: "Jacket", 
  price: "59.99", 
  currency: "EUR", 
  qty: "1"
}

const cart = [shirt, jacket];

const shippingFeePerItem = 3.99;

function calcShippingFee(cart) {
  const totalItemCount = cart.reduce((previous, current) => {
    return previous + current.qty
  }, 0)
  return totalItemCount * shippingFeePerItem
}

console.log(calcShippingFee(cart)) // 43,89
Enter fullscreen mode Exit fullscreen mode

You can probably spot the mistake right away? Let's to the same, this time typed out:

type Item = {
  name: string, 
  price: string, 
  currency: string; 
  qty: number
}

const shirt = {
  name: "Shirt", 
  price: "19.99", 
  currency: "EUR", 
  qty: "1"
}

const jacket = {
  name: "Jacket", 
  price: "59.99", 
  currency: "EUR", 
  qty: "1"
}

const cart: Item[] = [shirt, jacket];

const shippingFeePerItem = 3.99;

function calcShippingFee(cart): number {
  const totalItemCount = cart.reduce((previous, current) => {
    return previous + current.qty
  }, 0)
  return totalItemCount * shippingFeePerItem
}

console.log(calcShippingFee(cart)) // Still 43.89
Enter fullscreen mode Exit fullscreen mode

Now remove the quotation marks from around the qty property of both items, pat your junior on the shoulder and say "We've all been there".

And yes, you could have achieved the same behavior with JSDoc & The JS/TS check. Just like your junior could have ignored this mistake and ship the whole thing, causing havoc at checkout. Because no compiler could stop him.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

Regarding 'Why bother creating a new one?'. Because competition is good for innovation. I don't see competing standards as a bad thing.

I completely agree; competition is not a bad thing. In fact, it can be quite healthy and motivating. However, I think the key point here is that the mentality has shifted over the years from static languages to more flexible, dynamic ones. And now we are seeing a move back to static languages. This begs the question of why we are now moving backward. Transitioning from dynamically typed language to statically typed ones?

I think it's important to keep in mind that while competition is definitely a good thing, we also need to be careful not to get too caught up in it. There's a fine line between healthy competition and unhealthy obsession, and it's important to make sure we don't cross that line.

TS is superior to JSDoc in terms of static type checking in every way.

Still can't see why it is superior.

Can you verify this? I found it hard because I never worked with static types before. And I would argue that the hardest part is to learn the syntax - which is true for all other languages. I think it's really hard for developers who are just starting using ANY language.

Yep.

'JSDoc to be looks more verbose than Typescript based on the lines of text added to a particular file'.

How? Here is a good comparison between the two.

image

I stated that JSDoc has no compiler

As mentioned in the article, This is intentional, as having a compiler would slow down the development process. JSDoc is intended to be used as a documentation tool, and not as a means of adding code generation or validation. Still, it is possible to use JSDoc for these purposes.

You can ship incorrectly typed code (could have errors, could have none)

JSDoc will not stop you, because there is no compilation step involved.

I would argue that JSDoc's lack of a compiler can be seen as a positive thing. The need for a compiler would slow down the development process, and JSDoc's focus on documentation over compilation means that it can be used more quickly and easily.

I love Javascript's anarchistic approach to dynamic types, it's what opened the gate to programming to me.

Same.

I've seen horrible crimes being comitted using Vanilla JS - Syntax in non-strict mode.

Again, for forgiveness' sake. If there are good QA / development philosophies followed, we are good.

And yes, you could have achieved the same behavior with JSDoc & The JS/TS check.

That's the main point.

Just like your junior could have ignored this mistake and ship the whole thing, causing havoc at checkout. Because no compiler could stop him.

It is true that mistakes are inevitable, but it is also true that when the right DevOps philosophy is followed and implemented, it helps to prevent and minimize the chances of making any mistakes. The key thing here is to have an understanding of what works for your team and business and then build a reliable system around it.

This could include setting up guidelines for code review, automated tests, deployment processes, etc., to ensure that only quality code makes its way into production. Additionally, having a correct monitoring strategy in place can help you detect problems in the system before they become too big and cause disruption.

The moral of the story is that while dynamic languages offer flexibility, static typing gives us safety and security when coding. So although moving from statically typed languages to dynamic languages may feel like a step backward, in reality, it is a step forward in terms of overall efficiency and productivity.

Thread Thread
 
tqbit profile image
tq-bit

I think we've reached a sweet spot in our discussion, so I'd like to finish with one last comment.

The key thing here is to have an understanding of what works for your team and business and then build a reliable system around it.

Additionally, having a correct monitoring strategy in place can help you detect problems in the system before they become too big and cause disruption.

This sounds a lot like having an additional step in between development and production. Like compilation.

You argued that a compiler slows development down. Then I'd say: Let's ditch QA altogether, like that we reduce our time to market by another 25%. Also, let's ditch all modern frameworks and write monolithic CSS again. Na, why bother writing classes? Inline CSS is the way, because with our IDE, we can do a mass-replace anyway. Or let AI handle the complex stuff (this seems like a real alternative by now).

Your code example gave me the shivers btw. I've seen a dev in my previous org naming all function arguments param1, param2, param3, ... . That went up to 12 args in one function.

Your comments seem a bit redundant and cover up for missing function context, so allow me to add another example here in TS, without the verbosity:

function tsCreateSum(first: number, second: number, third: number, fourth: number, fifth: number): number {
  return first + second + third + fourth + fifth;
}
Enter fullscreen mode Exit fullscreen mode

By proper naming, you can actually reduce the amount of comments you need. This is a simple example, so let me give you another in TS and JS.

The following code will read a file from a local machine. It can read it in three different ways: Buffer, JSON or String.

import fs from 'fs/promises';
import path from 'path';

const somePath = path.join(__dirname, '../settings.json');

async function readFile(
    filePath: string,
    readAs: 'string' | 'buffer' | 'json'
): Promise<string | Buffer> {
    const fileBuffer = await fs.readFile(filePath);

    if (readAs === 'string') {
        return Buffer.from(fileBuffer).toString('utf-8');
    }

    if (readAs === 'json') {
        return JSON.parse(Buffer.from(fileBuffer).toString('utf-8'));
    }

    if (readAs === 'buffer') {
        return fileBuffer;
    }

    throw new Error(`Cannot read settings as ${readAs}. Valid types are 'string', 'buffer', 'json'`);
}

readFile(somePath, 'string');
readFile(somePath, 'buffer');
readFile(somePath, 'json');
Enter fullscreen mode Exit fullscreen mode

Here's what I came up with in Javascript applying the same logic as you did above:

import fs from 'fs/promises';
import path from 'path'

const p = path.join(__dirname, '../settings.json')

/**
 * @description Reads a file from the local file system. 
 * @param {string} p The path from which to read the file
 * @param {'json' | 'string' | 'buffer'} r The type as which to read the file
 * @returns {Promise<string | Buffer>} The content of the file 
 */

async function jsRead(p, r) {
  const fb = await fs.readFile(p);

  if(r === "string") {
    return Buffer.from(fb).toString('utf-8');
  }

  if(r === "json") {
    return JSON.parse(Buffer.from(fb).toString('utf-8'));
  }

  if(r === "buffer") {
    return fb;
  }

  throw new Error(`Cannot read settings as ${r}. Valid types are 'string', 'buffer', 'json'`);
}

jsRead(p, 'string');
jsRead(p, 'buffer');
jsRead(p, 'json');
Enter fullscreen mode Exit fullscreen mode

The only thing that changed is that I moved all the information out of the function and put it above, creating 4 additional lines of code I could have saved.

While this example is very specific, you can see an increase of ~12% in textual content (lines and signs)

  • 29 lines became 33
  • 698 signs became 793

In a real project, this value might be significantly smaller, but If I can save 4 or 5% in a project with thousands of lines of code while increasing readability AND have static type checks AND I have a DevOps pipeline in place anyway, I'd be willing to pay the price of using a compiler.

Thread Thread
 
wiseai profile image
Mahmoud Harmouch

This sounds a lot like having an additional step in between development and production. Like compilation.

I would say yes, but it is not necessarily the case. A compilation is not necessary as an additional step between development and production. Someone may argue that TDD could be this step.

Your code example gave me the shivers btw. I've seen a dev in my previous org naming all function arguments param1, param2, param3, ... . That went up to 12 args in one function.

I think you missed the point I was trying to make. I'm not arguing about the naming conventions, I'm just showing how the function definition line becomes so fat/bloated without using JSDoc. I mean, have a look at this line:

function tsCreateSum(first: number, second: number, third: number, fourth: number, fifth: number): number
Enter fullscreen mode Exit fullscreen mode

Instead, JSDoc offers the most convenient way for both documentation and type checking (with CheckJS).

/**
 * @param {number} first - The first number.
 * @param {number} second - The second number.
 * @param {number} third - The third number.
 * @param {number} fourth - The fourth number.
 * @param {number} fifth - The fifth number.
 * @returns {number} - the result.
 */
function jsCreateSum(first, second, third, fourth, fifth)
Enter fullscreen mode Exit fullscreen mode

This will make your function easier to read without the need to scroll horizontally. So, I think with JSDoc, it's arguably much easier to understand what's going on.

By proper naming, you can actually reduce the amount of comments you need.

This opens up a whole new debate: Code Documentation VS Good Naming Convention.

The following code will read a file from a local machine. It can read it in three different ways: Buffer, JSON or String.

But the first example doesn't have documentation. If you use TSDoc, you will end up with the same number of lines in both examples.

Collapse
 
ndaidong profile image
Dong Nguyen

Totally agree with your arguments. The biggest strength of JavaScript is its simplicity and flexibility. I love the natural beauty of its syntax.

The abuse sometimes turns the source code into something horrible!

type PartialK<T, K extends PropertyKey = PropertyKey> = Partial<
  Pick<T, Extract<keyof T, K>>
> &
  Omit<T, K> extends infer O
  ? { [P in keyof O]: O[P] }
  : never
Enter fullscreen mode Exit fullscreen mode

If tc39 wants to make it a statically typed language, I hope that it should be something lightweight similar to type hints in Python.

When I need a strongly typed language, I would choose Vlang or Golang.

Collapse
 
wiseai profile image
Mahmoud Harmouch

If tc39 wants to make it a statically typed language, I hope that it should be something lightweight similar to type hints in Python.

Same.

Collapse
 
romeerez profile image
Roman K

I agree such TS code is hard to grasp and maintain. But it's not fare to say that Golang is better at this. It's impossible to write complex types in Golang, and if you like this inability - just don't write complex types in TypeScript!

 
derappelt profile image
Simon Appelt

Don't get me wrong, i'm a full time Vue developer and I like Vue way more than react. But to say something is objectively better is nonsense.
It completely depends on the goal you have.
Lot of you points are totally irrelevant in certain situations. Even though you can measure them.
It's like saying bicycles are better than cars because they are objectively lighter.

Thread Thread
 
jackmellis profile image
Jack

That's it I'm swapping my car for a bicycle tomorrow!

Collapse
 
fyodorio profile image
Fyodor

It's sad to see such a hype and such a negativity in comments at the same time. It feels like folks are offended and just afraid to accept that they had spent a huge amount of time for worthless knowledge. Take it easy guys, TS is legit which doesn't cancel legitimacy of the author's points. Be brave to accept: TS is not ideal, and not fun at ll in terms of DX. It became neither fish nor fowl.

This is a goto technology for big teams because many developers just don't give a funk about writing good code and TS forces some good practices. But at the same time, we all saw a lot of examples of great software written in JS, and awful software written in TS.

So the truth is: TS is not better than JS.

Other truths are relevant and contextual.

Collapse
 
wiseai profile image
Mahmoud Harmouch

So the truth is: TS is not better than JS.

 ^
 |
 --- This!
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jaceromri profile image
Jacer Omri

I always try not to be harsh. I was going to say the only valid point in this article is the additional compiling step (bothers me personally) then I remembered it's the same deal with babel, as you need to use it (unless it's not a serious project). All the other points can be attributed to lack of understanding or knowledge about things like tsconfig. The typing system is the solution we got to have to solve bomb-like errors in runtime caused by typos or mis communicated documentations. Try to think of how much lines of code you would write to just check if the params passed to a function call are valid. If you're gonna bring up flow or jsdoc, other commenters already said enough about it (obsolescence, lack of basic functionalities...). I've been doing JS in the backend and frontend for more than 10 years, the only JS projects that survive are those written in TS. You can tweak for performance and regain it, but you can't sacrifice code quality, sophisticated integrated documentations and universal understability of the project by any developer.

Collapse
 
leob profile image
leob

Well said - TS is all about increased levels of rigor and quality, as an antidote to the prototypical (pun intended) nature of JS "cowboy coding" ... the author's article mentions "17 reasons", but not 17 compelling reasons :)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

14. Wow. Just wow.

It says:

That's because the TypeScript organization/structure imposes a runtime performance penalty.

When? Where? How? Do you know how TypeScript works? Like at all? TypeScript only has shims. If a new variable appears in front of you that somehow magically underperforms, guess what? It is your own fault.

You either write performant code that TS doesn't have to figure it out, or you type TS that works the way it is intended. If a shim for older JS is giving you a hard time, simply stop depending on said shim. My God! This is one of those articles that should just be deleted. Free speech, I guess. This reminds me about the guy that was trying to convince people DRY is bad.

Collapse
 
seanmay profile image
Sean May

I mean, taken as a maxim, and applying no further thought, DRY is terrible. Especially when coupled with OO inheritance.

Collapse
 
webjose profile image
José Pablo Ramírez Vargas

People fear OO soo much and I don't know why. Yes, I know all about the composition over inheritance argument, but OO, as you place it, is not the devil. I do OO quite often with superb results. And I kind of do take it as a maxim. I hate copying and pasting from one place to another. I literally forbid this practice to myself.

Thread Thread
 
seanmay profile image
Sean May • Edited

The opposite of DRY isn't copy+paste. Not adhering to DRY is simply typing the same thing more than once. Typing for (int i ...) more than once would be a violation, if you take it literally enough. Which actually makes FP and declarative operations on sets a pretty sound way of reducing repetition.

Regarding DRY and inheritance, how do you get a Duck and a Penguin to extend Bird, without invariant problems that break the Liskov Substitution Principal of any subtype S, being perfectly compatible with it's supertype?

Thread Thread
 
webjose profile image
José Pablo Ramírez Vargas

Are you really trying to imply that there's a difference between copying and pasting and manually typing the same thing ??? The end result is the same. This adds no value to the discussion.

Thread Thread
 
seanmay profile image
Sean May • Edited

So you only have one for loop in your codebase...

And how do you get a Square to inherit from a Rectangle, or a Circle to inherit from an Ellipse, without LSP violations? You wouldn't want to have both a Rectangle and a Square. That's wasteful and not DRY, in a world without nuance, so how do you do it?

DRY, without nuance leads to architectural nightmares, which lead to refactoring nightmares, which lead to a decade of the game industry just using god-blobs for literally every possible thing that could go through the engine... essentially having your object inherit from the object type that has every property and every method possible in the system, and then just praying you don't call the wrong one on the wrong thing at the wrong time.

Thread Thread
 
smolinari profile image
Scott Molinari • Edited

This discussion brings up some thinking I constantly have. Some people (too many) contend that JavaScript isn't an OO language. However, that is absolutely wrong. It's an OO language through and through, but without the need to have classes for object instantiation. Yes, the ECMA group broke down and offered classes in ECMA Script 2015/ES6, but you still don't need them to get objects in JavaScript. And because of this "class rules them all" thinking, you also get the misconception of what OO is all about. It's not about class constructs, it's about designing software around objects......no matter how they are created. And thus, people who stay very high-levelish with their understandings of OO programming misconstrue the lack of having classes to be "it's not OO". So, so wrong....

Out of that and back to the subject, class inheritance in a class based language is definitely a really bad form of coupling. And to me, this is where JavaScript shines. Because with its protypal inheritance modal, Mr. Eich tried to "lock away" the issues of class based inheritance. And yes, you can still do other very bad things with this form of inheritance too. But, the goal was, to help the developer avoid the class inheritance issue altogether, by, wait for it, not needing classes to instantiate objects. Woohooo!

In the end, understanding what it means to have inheritance between object defining constructs and why it can become total evil if the depths of the hierarchy become too deep, should be one of the basic teachings for any noob developer. That is when "composition over inheritance" should also be taught (along with other basics in software architecture and design).

Scott

Collapse
 
thm_33 profile image
Thomas Valadez

This is a very verbose and well articulated opinion.

As someone who has been using TS for about 3 years now, I would like to point out that many claims in this are very much conjecture rather than substantive analysis of Typescript.

TS doesn't restrict JavaScript because it is all removed at runtime. It only gives you a false sense of security if you have not typed your code properly.

TS is a very powerful tool and, to the authors credit, it does come with a learning curve. The bottom line though, like any other tool, it is only as useful as you make it.

Collapse
 
longebane profile image
Long Dao • Edited

Verbose and well articulated.. I'm not sure of that. This article felt to me like he just sat and thought long and hard about every point he hated about ts (regardless if some of the points are a reach). And then, like a school student trying to fill in a word quota, padded out a lot of his points with surface filler or purposely cherry-picked examples of convolution to illustrate his point (ie his bubblesort example). Not good faith

Collapse
 
mellen profile image
Matt Ellen

JavaScript is fine! ✅
Types aren't that useful! ✅

You have my vote for president.

Collapse
 
strongunsullied profile image
Kasope Johnson

I think you should put in actual work to learn typescript. This is just basically a hate article on TS

Collapse
 
wiseai profile image
Mahmoud Harmouch

I think you should put in actual work to learn typescript.

Define "actual work". Should I open an OnlyFans account and start sharing exclusive TypeScript content, or what?

This is just basically a hate article on TS

Nope. Not at all. This proves that you didn't even bother reading the conclusion.

Collapse
 
spock123 profile image
Lars Rye Jeppesen

I'm not sure I'd pay for that lmao :)
But idea should be tried out for sure. Just remember to wear the right attire :)

Collapse
 
strongunsullied profile image
Kasope Johnson

😂
Sorry for my aggressive tone
I just really don't think those reasons are valid.

Not sure I would pay for that too 😂

Collapse
 
camelioe profile image
camelioe

😂😂😂😂😂😂

Collapse
 
awolokita profile image
awolokita

Good luck refactoring / modifying a huge code base that isn't written in a strictly typed language. That is, unless your team has covered the type-level contracts with unit tests; which I highly doubt if they're been convinced by any of your arguments to ditch Typescript.

Collapse
 
leob profile image
leob

I think refactoring is the most compelling reason why TS is a good thing (and code navigation is a strong reason as well).

Some comments may only be visible to logged-in visitors. Sign in to view all comments.