DEV Community

Discussion on: To Typescript Or Not To?

Collapse
 
vagrantjin profile image
Vagrant Jin Kazama

TS which has one of the most advanced type systems out there

TS compiler is pretty fast and there is also Deno which runs TS out of the box, without compilation to JS.

And that's exactly the problem which makes all dynamic languages bad for large projects. It's been empirically proven that large projects benefit from using types.

Your answer reads like an ode to complexity. I feel I have to defend the "old" languages.
Complexity justifies the high salaries developers command for their monthly paycheck, rather than good, simple, clean, readable code.

And to further my status as a consultant and heathen, why is JS being used everywhere? If you yourself say static typed languages are superior, why not use a static-typed language, instead of added complexity and overhead to bend the time-space continuum of a dynamically typed language to do the work? Why not use C# or Java on the backend? Why add an order of magnitude more complexity to client side code?

You know the answer. I know the answer. Cleverness.

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

Your answer reads like an ode to complexity. I feel I have to defend the "old" languages.
Complexity justifies the high salaries developers command for their monthly paycheck, rather than good, simple, clean, readable code.

Your thoughts come from the wrong premise. Types don't add to the complexity that much. Yes, it's more work, but it will be complex as much as your project is complex.

Java is not inherently more complex just because of it being static typed. It's more complex because of it's huge ecosystem and the things you can do with it. Java on it's own is pretty straight forward language. TypeScript too. Types don't change that.

I'm always for the simple, clean and readable code and that's exactly one of the reasons why I prefer TypeScript - because I can clearly see what my method takes as arguments and what it will return. The code is self documenting.

And to further my status as a consultant and heathen, why is JS being used everywhere?

It's not used everywhere. We can easily get that impression if we're working solely on the web or we heard how it can be used for embedded applications, desktop applications and so on. Just because something can be used in many places doesn't mean it should be.

PHP could be used for writing desktop applications too, and how many popular desktop applications you know which are written in it? Compared to that there are some popular desktop applications written in JS but most of them suffer from performance issues when you're trying to deal with more CPU intensive stuff. VS Code is an exception because Microsoft invested heavily in making Electron more performant.

If you yourself say static typed languages are superior, why not use a static-typed language, instead of added complexity and overhead to bend the time-space continuum of a dynamically typed language to do the work? Why not use C# or Java on the backend? Why add an order of magnitude more complexity to client side code?

Because I don't get to choose which language we will use on the project. I'm working as a full stack developer on mostly JS projects which all use TypeScript. If I'm given a chance to choose between TS or JS, I'll choose TS. If I'm given a chance to choose between JS and X language for the back-end, where X is Java, C#, Elixir (which is dynamic typed language by the way) or some other technology interesting to me and suitable for the project, I'll choose X.

So yeah, I would use C# or Java on the back-end if I had chance.

You know the answer. I know the answer. Cleverness.

Nope, just gave you the answer above. It's about business decisions.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇

I've something to say in here.

  • Java is complex because it adds so many boilerplate that it makes it hard to read. Kotlin solves some points of that but not all of them as well.

example of java code:

public static String testableHtml( PageData PageData, Boolean IncludeSuiteSetup) {
   PageData foo = new PageData( PageData );
   String a = foo.getName();
   // do stuff

   return  a;
}

How this can be more readable?

/* @ params
* PageData, Boolean
* return String
*/
public static testableHtml ( PageData, IncludeSuiteSetup ) {
    foo = new PageData( pageData);
    Sring a = foo.getName();
   // doStuff;
  
   return a;
}

It's a simple example where not so bloatware is added but imagine that on a really big project, having to read the types all the time of you try to figure out what the code does. if you equal a var to a given type, it's inherent that it will take this type.

TS does a better job than Java in this point, for example.

PHP could be used for writing desktop applications too,

When I was a young dev there was a framework for doing that. Of course it embedded an Apache server (I guess) that were virtualised inside this environment to reach that. It was slow because the current tech didn't exists.

PHP like any other interpreted language nowadays is compiled when interpreted for the first time so the server can read the compiled version to run faster. Same happens with JS or Ruby to say some. It also wasted resources to raise this "VM" environment on a time where resources were more limited than nowadays.

Each language has 1 or more runtime environments and PHP as desktop APP have some throwbacks for it not being recommended.

JavaScript by the other hand has to consume notably less resources to run and has an advantage for the implicit way it runs, which leads to more efficiency than PHP (we can enter in more detail about that whenever you want).

... I'm working as a full stack developer on mostly JS projects which all use TypeScript. If I'm given a chance to choose between TS or JS, I'll choose TS. If I'm given a chance to choose between JS and X language for the back-end, where X is Java, C#, Elixir (which is dynamic typed language by the way) or some other technology interesting to me and suitable for the project, I'll choose X.

As I've said before TS is good but using always TS is usually a lack of previous analysis of what you really need. There's no tech to rule them all and all of them cover some needs.
If you are going to make a whatsapp knock-off or audio stream such spotify, you can use Java to deal with this Async operations, which will be a pain in the ass compared to using JS over Node, the dev time will increase notably and the end result will not differ much from one implementation to another, so there's no reason for not using JS on that (to say something).

As second example (and the last to not extend this comment more) would be using TS on a simple Node API that's a CRUD for -let's ssay- email and password of the user profile.

You'll end up with 50-70 lines of code as much, they will be listeners to some route with some resolver in it, well structured. There's no real need or concern that leads you to use TS here. The same way not all things have to be OOP.

Again, analysis part is one of the most important things when starting a project or a new feature. Then having your code to work is half the job while cleaning your code is the other half.

Stay save and code tests,

best regards :)

Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

Java is complex because it adds so many boilerplate that it makes it hard to read. Kotlin solves some points of that but not all of them as well.

Again, this is subjective opinion. Just because there is more to read doesn't mean it's inherently harder to read - you just have more information, but I only see this as a plus because there is no place for ambiguity compared to reading JS (except if you're writing JSDoc, which is less ideal solution than having types where declarations are).

You ask how this can be more readable - it's pretty easy to read for me. Right away I see it's a static method which returns string and takes too parameters, one which is an instance of the PageData and other which is a boolean. I don't understand what's so unreadable here.

It's a simple example where not so bloatware is added but imagine that on a really big project, having to read the types all the time of you try to figure out what the code does. if you equal a var to a given type, it's inherent that it will take this type.

You don't have to spend all your time reading types. Java also introduced var some time ago so you don't have to write huge lines anymore. Most of the types you'll work with will be straightforward, except if you're working on something more complex, in which case it would be of even bigger help to have types in the first place.

JavaScript by the other hand has to consume notably less resources to run and has an advantage for the implicit way it runs, which leads to more efficiency than PHP (we can enter in more detail about that whenever you want).

I agree, but the fact stays that it's not good for CPU intensive tasks (except if you're using some multi threaded environment which are rare - Electron uses V8).

As I've said before TS is good but using always TS is usually a lack of previous analysis of what you really need. There's no tech to rule them all and all of them cover some needs.
If you are going to make a whatsapp knock-off or audio stream such spotify, you can use Java to deal with this Async operations, which will be a pain in the ass compared to using JS over Node, the dev time will increase notably and the end result will not differ much from one implementation to another, so there's no reason for not using JS on that (to say something).

If I need to use JS, I don't need any specific analysis for TS because TS is JS after the compilation step kicks in. JS with much less headaches in every sense. There is no one technology to rule them all, but when I see that JS is suitable, even if I'm going to write a small CRUD app with few routes. It's because TS gives me so many benefits over using purely JS and I mentioned these benefits before. Why would I make my life harder if I don't have to?

If you are going to make a whatsapp knock-off or audio stream such spotify, you can use Java to deal with this Async operations, which will be a pain in the ass compared to using JS over Node, the dev time will increase notably and the end result will not differ much from one implementation to another, so there's no reason for not using JS on that (to say something).

It doesn't have to be pain in the a** if you know what you're doing. There is Akka. If you need to do CPU intensive stuff on top of dealing with async operations it makes more sense to use Java. If you don't and your developers know JS better, it makes more sense to use Node. There are many questions you have to answer before choosing a technology and there are reasons not to use JS even if you're doing async stuff - if it wasn't the case no one would use Go, Elixir, Erlang and other languages for that purpose.

Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇
Again, this is subjective opinion. Just because there is more to read doesn't mean it's inherently harder to read

Yes it is, and it's nothing new, in times of Aristotle they already studied how the way to spell/write things down can change the perception and the attention of the people.
If you say/write something concisely, using the context people will bring more attention but if you add repetition and don't use the context people simply stop paying attention to your speech or text.

This, in programming languages (remember that it's just a language, not to communicate between people but to communicate with a machine, even that, who had to read this language are other people as well) is translate as which we know as boilerplate.

the java syntax (unless you use var, ok) is repetitive and doesn't make use of conversational context.

String a = "foo";
String b = a;

you need to declare the type on the second one even being a copy of the first.

let's set an example in prose:


The women were in the blue house at the top of the mountain, waiting for the sunset.
The blue house at the top of the mountain was being stalked by an strange creature, but the women feel safe inside the blue house at the top of the mountain.

It's detailed, of course but it's hard to keep your attention to this and remember all the stuff you are reading, because people have context, and we're animals that like other animals, want to reach a given situation as fast or efficient as possible, so we like to read like this:


The women were in the blue house at the top of the mountain, waiting for the sunset.
The house was being stalked by an strange creature, but they feel safe inside the house.

Knowing what is easier to read it's a scientific fact and not an opinion.


If you need to do CPU intensive stuff on top of dealing with async operations it makes more sense to use Java. If you don't and your developers know JS better, it makes more sense to use Node. There are many questions you have to answer before choosing a technology and there are reasons not to use JS even if you're doing async stuff - if it wasn't the case no one would use Go, Elixir, Erlang and other languages for that purpose.

You can simply set a Node server to handle requests and resolve CPU intensive tasks specifically inside Python or Java or... APIs/web services.
You can benefit of faster development production and good performance as well. Having devs knowing a specific tech is an important part of the decision but never should be the most important part.

It's cheaper to pay a course to your devs and develop with the right current stack than using a wrong one because is "what they already know". Also devs usually like to learn new things so they'll feel like they are learning on it's current job and will probably be more excited about starting on a greenfield with a new tech.


If I need to use JS, I don't need any specific analysis for TS because TS is JS after the compilation step kicks in. JS with much less headaches in every sense. There is no one technology to rule them all, but when I see that JS is suitable, even if I'm going to write a small CRUD app with few routes. It's because TS gives me so many benefits over using purely JS and I mentioned these benefits before. Why would I make my life harder if I don't have to?

Here I let you a simple get and put verbs from an hypothetical API (there's a nonsense on adding the rest of the verbs because it will be a repetition of those actions mostly) with dummy data.

Do the exercise and translate this into TS and show which benefits can you get from that:

const Joi = require('joi');
const express = require('express');
const app = express();

const courses = [
    { id: 1, name: 'First Course 1' },
    { id: 2, name: 'Second Course 2' },
    { id: 3, name: 'Third Course 3' },
];

app.get('/api/courses', (req, res) => {
    res.send(courses);
});

app.put('/api/courses/:id', (req, res) => {
    const course = courseExists(req.params.id);
    if (!course) return res.status(404).send('The course with the given ID was not found');
    
    const { error } = validateCourse(req.body);

    if (error) {
        let errorMessage = '';
        error.details.forEach( err => {
            errorMessage += err.message
        });
        return res.status(400).send( errorMessage );
    }

    course.name = req.body.name;
    res.send(course);
});

function validateCourse(course) {
    const schema = Joi.object({
        name: Joi.string().min(3).required()
    });
    return schema.validate(course);
}

function courseExists( id ) {
    const course = courses.find( c => c.id === parseInt(id) );
    return course;
}

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

If you say/write something concisely, using the context people will bring more attention but if you add repetition and don't use the context people simply stop paying attention to your speech or text.

Can you show me exactly where is this repetition you're talking about? Because declaring something as a String and writing down the string precisely character by character later is not a repetition. Declaring a type and defining a value is not the same, and as I said, type inference is available in Java today, so there are even less reasons to talk about some repetition, especially when it makes code clearer to understand. When you write something like this;

const processQueue = ({ queue }) => {
  // do something with the queue
}
Enter fullscreen mode Exit fullscreen mode

How do you know what's the queue? What it contains? What methods you can call on it? It's easy to read but it doesn't give you any information. Not to mention that you need to define type so that compiler can know what will that variable contain if you're not passing value immediately. Compiler can't predict what you're going to put in it.

This, in programming languages (remember that it's just a language, not to communicate between people but to communicate with a machine, even that, who had to read this language are other people as well) is translate as which we know as boilerplate.

Actually, programming languages we use today were developed so people can better communicate between themselves about what the program does. If that wasn't the case we would still use Assembly or other lower level languages.

Remember what Harold Abelson said;

Programs must be written for people to read, and only incidentally for machines to execute.
Enter fullscreen mode Exit fullscreen mode

It's detailed, of course but it's hard to keep your attention to this and remember all the stuff you are reading, because people have context, and we're animals that like other animals, want to reach a given situation as fast or efficient as possible, so we like to read like this:

Except our jobs as a software engineers is not to look at things from the animalistic perspective but rationally.

It's the empiric fact that types make development easier by describing the possible way some data can be processed. Yes, you write more code, but it's an investment for the future. Next time I come to the part which was self-documented by using types I'll have much less troubles understanding what has to be done.

Having to spend a bit more time to read it is a trade-off which you have to pay for more thorough explanation, but that will remove ambiguity and possible problems in the future stemming from that. Slower is faster.

Knowing what is easier to read it's a scientific fact and not an opinion.

And as I already said - harder to read != more complex.

You can simply set a Node server to handle requests and resolve CPU intensive tasks specifically inside Python or Java or... APIs/web services.
You can benefit of faster development production and good performance as well. Having devs knowing a specific tech is an important part of the decision but never should be the most important part.

It's cheaper to pay a course to your devs and develop with the right current stack than using a wrong one because is "what they already know". Also devs usually like to learn new things so they'll feel like they are learning on it's current job and will probably be more excited about starting on a greenfield with a new tech.

Okay, now we're getting into nitty gritty details and I think you're not really getting me right, so let's put things straight.

I never said that some technology should be used just because developers already know it. It's one of the points you use to choose technology - as I said, there are many points you have to discuss. If we all know JS and JS is not the right thing to use, we won't use it. In your post, you made it look like JS is the only choice for doing async stuff - it isn't, nor it's the best one. It's just that, a choice. Whether someone will use it or not depends on many other factors as well. You can't ignore the fact that market also dictates the choice of technologies, otherwise many of them would never even be chosen anymore for the new projects.

Here I let you a simple get and put verbs from an hypothetical API (there's a nonsense on adding the rest of the verbs because it will be a repetition of those actions mostly) with dummy data.

Do the exercise and translate this into TS and show which benefits can you get from that:

const Joi = require('joi');
const express = require('express');
const app = express();

interface Course {
  id: number;
  name: string;
}

const courses: Course[] = [
    { id: 1, name: 'First Course 1' },
    { id: 2, name: 'Second Course 2' },
    { id: 3, name: 'Third Course 3' },
];

app.get('/api/courses', (req, res) => {
    res.send(courses);
});

app.put('/api/courses/:id', (req, res) => {
    const course = courseExists(req.params.id);
    if (!course) return res.status(404).send('The course with the given ID was not found');

    const { error } = validateCourse(req.body);

    if (error) {
        let errorMessage = '';
        error.details.forEach( err => {
            errorMessage += err.message
        });
        return res.status(400).send( errorMessage );
    }

    course.name = req.body.name;
    res.send(course);
});

function validateCourse(course: Course) {
    const schema = Joi.object({
        name: Joi.string().min(3).required()
    });
    return schema.validate(course);
}

function courseExists(id: number): Course {
    const course = courses.find( c => c.id === parseInt(id) );
    return course;
}

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
Enter fullscreen mode Exit fullscreen mode

I get multiple benefits;

  • Right away I see what parameters my method takes and what it will return
  • I won't be able to accidentally pass a course with the wrong structure (you may say it's really hard for this to happen because I'm just changing a single array, but there is still a possibility so - no need to risk)
  • I get better help from IntelliSense
  • Code is more ready for the future if I want to make the project bigger. I can just move interfaces to their own files and keep all the benefits I mentioned above.
Thread Thread
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

now that's a well defined answer where you are right on everything not because you wanted to explain it since the beginning but just why I told you things that were inexact or "falsy" so you want to put the things straight like they are.

That is the kind of explanations that most people need because If it was true that I knew nothing about that and I were talking serious in my sentences, now I could understand what's going on there, even if it's a little bit.

That's the main purpose of this circus and in most cases it's not people not knowing things, it's that people (like you and myself) write down things without really analysing or going in detail, or finding which details are needed to fully understand the topic. Which is normal because we take for granted things that we already know.

I truly believe that if we can answer in comments or explain in posts the things like we do when we're pissed, newcomers could inherit this knowledge, connect the dots and maybe, some day -hopefully sooner than later- became better than us.

I've three more things to say:

  1. Thanks you.
  2. Sorry for making you loose some time.
  3. You can be a good speaker/teacher/writer on this subjects when you want.
Thread Thread
 
stojakovic99 profile image
Nikola Stojaković

No worries. It was indeed an interesting exchange of thoughts. All the best!