Is it possible to "force" Javascript typing?

Asked

Viewed 1,335 times

7

In PHP I’m used to creating a function and can declare the types of parameters I want, even knowing that the language is weakly typed, but in JS I can do this?

Example in PHP:

<?php

class Teste {

    private $names;

    /**
     * setNames
     *
     * @param array $name
     *
     * @return void
     */
    public function setNames(array $names) {

        $this->names = $names;

    }

    /**
     * getNames
     *
     * @return array
     */
    public function getNames() : array {

        return $this->names;

    }
}

$nome = new Teste();

$nome->setNames('Lucas');
var_dump($nome->getNames());

Will give the error:

Argument 1 passed to Teste::setNames() must be of the type array, string Given

1 answer

14


Declaring types has nothing to do with language being strongly typed. In fact, it’s not even being statically typed, which I think is what I meant. You can read more about this at What is the difference between a static and dynamic programming language?. People use the terms mistakenly because they don’t understand the right concepts.

In fact PHP and Javascript are weakly typed and dynamically typed. PHP started to allow to put types and impose some limitation, although it remains dynamically typed. Helps, but does not make it statically typed.

If you need that kind of help, and it’s really good, you should probably use another language that is not only statically typed, but also strongly typed, which actually helps 100%. It makes no sense to use the wrong tool for the task. A language that started one way will never be good at the other. Even this way of programming is better to do in Java or C#, PHP should be simpler. The advantage of PHP is to be simple. When you start to program yourself Nterprise in it the tool becomes wrong.

Carro com um cavalo dentro no banco de trás com a cabeça para fora

Javascript has none of this and say it never will, so they created Typescript which solves much better, although not 100% by maintaining compatibility with JS. Unfortunately, although TS is statically typed most of the time, it is not always, it remains weakly typed and by converting to JS much of the advantage is lost, but I still consider it better for large code bases.

  • 1

    Excellent explanation!!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.