DEV Community

Discussion on: To Typescript Or Not To?

 
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!