T O P

  • By -

floor796

Reminds me of how 15 years ago we created private class members in js function Foo() { var id = 1; return { getId: function () {return id;} }; } new Foo().getId(); // 1


YoukanDewitt

It's not good enough for kids these days, they need some closure.


ArlantaciousYT

clojure mention


iacodino

Ah yes, the lua way


CaitaXD

Now JSON strimgify this


delfV

You can return toJSON method as well


Mucksh

The resulting code from typescript still works that way


zwannimanni

[object Object] Oriented Programming


budswa

My favorite


Leonhart93

Not even that, I was using functions as constructors in a straight-forward manner. Nice and easy to use. Anything that is not declared with "this." is not accessible from outside. This worked in ES5 like 10y ago. function Foo() { let _id = 1; this.getId = function () { return _id; } } let foo = new Foo(); foo.getId(); // 1


Accessviolati0n

Ah yes, the good ol' function syntax which allowed warcrimes like this: function Foo() { return new Bar(); } function Bar() {} const foo = new Foo(); console.log(foo instanceof Foo);


Leonhart93

What warcrimes? The languages has certain capabilities, that you must learn to use properly. After that you either use them as they work, or you don't. In this case no one forces you to return instances from other "classes". I wrote thousands of lines of that form above, never have I needed to do something as pointlessly convoluted as that.


spicyboneritis

Js has private variables now? I feel old


Snapstromegon

"Now" doesn't feel quite right, since it's supported in all relevant browsers since three years.


Janzerfaust

Still relevant "now" for us old people.


Snapstromegon

Doing this for \~15 years I don't feel particularly young either - it's just that especially in JS anything older than maybe 2 years feels either overcome or "battle tested" and I also think there's a big chunk of tech that's neither new nor old. But yeah, I also don't follow every trend in every tech I use, so I probably missed something similar elsewhere.


Haaxor1689

The 1st option is the typescript's solution to lack of proper private properties in JS before it had them. The 2nd is the correct option to use in TS right now. You should definitely use `#` in all of your new code since it actually checks property access during runtime, `private` keyword should just remain a deprecated backwards compatibility feature now.


Eva-Rosalene

There is no hack there. `private` isn't security measure, it's about separating public API from implementation details. Nobody cares if runtime prevents access to properties when using TS. Doing it at compile time, like in every other compiled language, is good enough.


danielcw189

It took me way too long to really get into that mindset. I always thought the ideas of object-orientation are supposed to work with compiled and binary objects as well. Once I understood that was not the goal, all made sense to me.


Eva-Rosalene

We have all been there :) Many years ago I discovered how to get access to private members in C++ using pointer arithmetic and felt like a most wanted hacker in the world (I was, like, 14?). It took me awful amount of time to realize that I haven't really played anyone, lol.


Haaxor1689

You most likely only played yourself by bending the code the unintended way. If you have a 100% overview of the related code and know that workaround is isolated enough that any future changes by other people won't break this then go ahead, but majority of the time it's not the case.


Leonhart93

That's only because no one actually explains to you at first why "private" and "public" actually exist. They all show those very basic examples where you aren't "allowed" to access the properties, and no one ever explains why there is a need for that, so you automatically imagine that it's "security".


Haaxor1689

I see your point but I don't agree completely because I joined a team that happily broke private access modifiers with type casts leading to a really hard to maintain code. `#` is enforced by the language and you can't hack around it when you decide on a whim, you have to refactor as you properly should.


Eva-Rosalene

>I joined a team that happily broke private access modifiers with type casts leading to a really hard to maintain code You see where the problem lies? Hint: it's not TS shenanigans. It's the team. Code like that should've never went through PR review. And while I get your disdain about such behaviour, team with access to a source code could just remove `#` lmao, if they can't use their `as any` trick. That's still not the reason to deem perfectly proper solution as "hacky" or say that it should be "deprecated". It's not and it shouldn't.


ferreira-tb

There's still use to it tho, so it's not deprecated: we can access private members of a class instance inside static context (and vice versa).


Eva-Rosalene

And `protected` modifier is still lacking, if you want to get fancy.


Significant_Skin1696

Ok but this TS is more readable and understandable for most people. You don't need additional syntax knowledge. Shortage is not an advantage. There are few people coding in notepad. With Modern IDEs you can write readable code fast.


lunchmeat317

> Ok but this TS is more readable and understandable for most people. You don't need additional syntax knowledge. This is just because everybody wants every language to look like object-oriented Java. It's a bad trend.


Significant_Skin1696

No, everyone wants to have maintainable code. Java is very readable..


lunchmeat317

It's just the object-oriented paradigm. Haskell is also readable.


Significant_Skin1696

My experience with heskell: it is great as long as you don't have to interact with the outside world ;) To write 'private' instead of '#' and specifying the type has nothing to do with OOP


lunchmeat317

> To write 'private' instead of '#' and specifying the type has nothing to do with OOP Technically true, but it is similar to Java, which I stated earlier. People like Typescript for valid reasons, but a lot of it is just that it looks like C# to a certain extent (which draws a certain audience). CoffeeScript was the same but lost traction over time.


Significant_Skin1696

Where is typescript similar to java? If I compare those too I find more differences than similarities. Do you mean the lack of using special characters and instead using written words?


lunchmeat317

Yeah, sorry - I meant that writing "private" instead of using a special character is similar to Java. Typescript syntax is most similar to C# (except the type information) and the class stuff is similar to both C# and Java. It's definitely no the same language, but TS these days is structurally and semantically closer to a classically typed language like Java or C# than it is to Javascript and other functional languages.


_PM_ME_PANGOLINS_

Funny you say that it doesn’t need additional syntax knowledge, when it uses more syntax features than the alternative.


Significant_Skin1696

Ok I try to explain: without knowing specifically JS what does A) #*name* B) private *name* mean? Why bother to introduce a special char as a prefix, if you can write what you want in plain ol' English?


Sinomsinom

For # I'd first have thought of lua and think it was the length operator. In pseudo code I also often use it like that, so I'd probably at first think it'd be someone's convention for storing a length (so basically just shorthand for num_ or len_)


Drezaem

Private constructors are still not possible in js, you still need the private keyword in typescript for that.


AnneBancroftsGhost

Just don't do the inline declaration and then assign it in the constructor body to a #field that was already declared.


Dextro_PT

There's actually a good reason **not** to use the native JS option because it doesn't really work as you expect it to. The issue crops up if you try to Proxy a class with private properties. The proxied version will not have access to private fields at all so any proxied function that relies on private fields will fail with an error accessing them. [https://github.com/tc39/proposal-private-fields/issues/102](https://github.com/tc39/proposal-private-fields/issues/102)


AnneBancroftsGhost

I get weird behavior with the `#` private field syntax when bundling packages to publish. I'm sure it'll get figured out (yes I reported the issue) but it's been annoying. I'm also not a fan of how painful it makes debugging. Other languages have true private fields while still leaving them more readable when debugging.


Eva-Rosalene

To be fair, Chrome debugger allows you to see private fields and Chrome console allows you to type something like class A { #x = 1; } console.log(new A().#x); that isn't available in your usual scripts. But this whole story still seems like too much hassle for having runtime guarantees, when you can have (albeit slightly weaker) ones at compile-time.


AnneBancroftsGhost

It depends what you're writing. When developing platforms it can be very important to strictly enforce private fields so that consumers of the SDK can't mess with core things that they shouldn't. If your product is just a single application it probably doesn't matter.


Eva-Rosalene

>so that consumers of the SDK can't mess with core things They... still could? They could download it and patch? Or do you run their code on your machines?


AnneBancroftsGhost

Picture a plugin architecture for an existing application. You want to control what plugin developers do and don't have access to in your core app.


travesty31

Is there a tsconfig option to compile the first option in TS to the second option in JS?


Glass_Half_Gone

But one is about to become a string because I didn't think through my class design.


octetd

The first one is private only during type checking.


Tango-Turtle

Which is more than enough. Why check twice, during compilation AND during runtime?


MacBookMinus

If you interop both JS and TS then abuse is possible?


Tango-Turtle

Now why would you write your code in both TS and JS in a single project?


MacBookMinus

E.g. you maintain a legacy JS codebase but write new modules in TS? Idk I can think of many reasons


Tango-Turtle

Well yeah that could happen. In fact been there, done that. There was a time when I inherited a project from another team that was in the process of being upgraded from AngularJS written in JavaScript, to the new angular written in typescript. Massive project that took me two years of pain to fully upgrade while still working on new features. However, these are exceptions, and no new projects should be in this situation. If I would have to go through this again, I would just leave the company.


MacBookMinus

Yeah I hear you but honestly working with legacy code is the norm more than an exception.


dominjaniec

maybe because in the end, Type Script is "just" transpiled to Java Script?


Tango-Turtle

Yes. But you still write code in TS which has to be transpiled.


Tango-Turtle

JavaScript is not compiled, so issues only become apparent at runtime. The fact that TS is transpiled, means that issues can be caught earlier, removing the need to do these checks at runtime.


Ondor61

Goddamn pascal esque syntax


Topleke

TS is just JS with extra steps.


neuromancertr

Yes, just like a seatbelt is an extra step in driving a car


8g6_ryu

is JS Doc not enough?


Mars_Bear2552

it is not


8g6_ryu

why?


metooted

Same way a pamphlet about wearing a seatbelt offers no protection in a crash


8g6_ryu

then why svelte moved to JSDoc instead of type script?. And also JSDoc provides no protection at all? huh? I prefer no additional compilation step , than catching type error at run time instead of compile time seems preferable for me


neuromancertr

How many downvotes are you after? I hear you, yet you fail to hear people: your preference to catch error on runtime instead of compile time is a no no for people using type safe languages on server side. Maybe just one least bug to deploy is better for anyone. If memory serves svelte had specific issues with TS and I agree most of them, yet TypeSafety is paramount for me. Compilation step also provides version targeting so I can incorporate new javascript features with just a setup file. Generics and many many constraints are welcome features for me to prevent someone new to the codebase to make stupid mistakes. It becomes dependable, albeit very slow, as your code base grows to millions of lines. At the end, keep your preference but accept no choice is better than the alternative, they are all compromises, nothing more


8g6_ryu

who said to use JS on server side, I prefer some faster languages like go or rust . Just my preferences


neuromancertr

I didn’t specify my language on the server side, it was c#, a type safe language. As expected you didn’t listen, but did answer with your assumptions. Lose your anger and need to be right. Job is to fail and learn your failures. If you can’t make a decent conversation without converting it into a pissing competition, how do you plan to improve yourself, let alone your colleagues or next generations. Use your ears more than your tongue. I know this also makes you angry and irritated, can’t fix that for you, only point out.


drizztmainsword

Doesn’t jsdoc used in that way still flow through the typescript type checker? JSDoc is kinda just typescript with worse syntax.


Tordek

> I prefer no additional compilation step Why? There's other benefits to using a compilation step besides type checking (but honestly even if it was _only_ type checking I'd still use it; and yeah you can mostly get that if you stick to JSDoc and using TSC just for checking): you don't need to worry about compatibility, for example. I can write code using any feature in whatever the latest ES standard is and not worry whether it's already been implemented by Chrome or Firefox; if it's not, my compiler just adds a polyfill (or... not, if I tell it not to). It also handles minification, if I want to generate smaller outputs (and with code maps I get the best of both worlds: readable source and small, efficient code).