DEV Community

Ayoub
Ayoub

Posted on

OOP JAVASCRIPT PROBLEM !!!

how define the type of variable in constractor javascript oo
Class Personne{
constractor(name){
this.name = name
}
}
how can i make the name type string

Top comments (9)

Collapse
 
tracygjg profile image
Tracy Gilmore • Edited

One option is to switch to TypeScript because, as others have stated, JS does not support static typing but TS can help.
A lower impact approach if you are using VSCode is to use type annotations.

class Personne {
    constructor(/** @type string */ name) {
        /** @type string */
        this.name = name;
    }
}

const person1 = new Personne('John');
console.log(person1.name); // 'John'
Enter fullscreen mode Exit fullscreen mode

However, I will not stop this sort of thing happening.

const person2 = new Personne(42);
console.log(person2.name); // 42
Enter fullscreen mode Exit fullscreen mode

But you could change the constructor to state,

this.name = `${name}`;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hoangtrinh profile image
Hoàng devtrai

well if you really want the constructor to only receive string, you can just throw an error if the parameter is not a string with "typeof"

if(typeof name !== 'string') throw Error('Only string is allowed you mother fucker');

but nowadays devs use Typescript instead, they can just config the compiler to fail the build if it's violate TS rules, like passing number into string

Collapse
 
adev03 profile image
Ayoub

thanks

Collapse
 
codingjlu profile image
codingjlu

I guess I'm not a dev then. Hmm?

Collapse
 
arnabxd profile image
Arnab Paryali • Edited
class Person {
  name: string;
  constructor(name: string){
     this.name = name
  }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

You don't. JS doesn't allow you to define the types of variables

This is not a problem, it's just a different way of doing things

Collapse
 
adev03 profile image
Ayoub

thanks

Collapse
 
rodrigocnascimento profile image
Rodrigo Nascimento • Edited

Javascript has dynamic typing system. So the interpreter will trye to assign a type in execution time.

If you really want to use a static typing you should try to use typescript.

Collapse
 
zougari47 profile image
Ahmed Zougari

Try this
this.name= String(name)