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
For further actions, you may consider blocking this person and/or reporting abuse
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
For further actions, you may consider blocking this person and/or reporting abuse
邱敬幃 Pardn Chiu -
S.S.Vikash -
Kafeel Ahmad (kaf shekh) -
keploy -
Top comments (9)
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.
However, I will not stop this sort of thing happening.
But you could change the constructor to state,
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
thanks
I guess I'm not a dev then. Hmm?
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
thanks
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.
Try this
this.name= String(name)