Live data from Hacker News

TypeScript is surprisingly ok for compilers

matklad.github.io

191–200 of 245 posts

Re: TypeScript is surprisingly ok for compilers

#191

Earlier quoted context omitted.

What you are advocating, the guessing about performance, is the premature optimization. Don't feel bad, most developers have no idea what that term really means. Here is the original essay where it comes from: http://web.archive.org/web/20130731202547/http://pplab.snu.a... Premature optimization is the extra effort required to alter work necessary to circumvent guessed optimization pitfalls. In the same breath Knuth…

> Don't feel bad, most developers have no idea Some advice I know you’ll ignore: your tone in the comments here is deeply patronising. You know absolutely nothing about me and yet are entirely comfortable dismissing my perspective as wrong simply because yours must be correct. It’s not an interesting or rewarding way to converse, it makes me want to stop talking to you as soon as I can. Which I’ll be doing here. Have…

Yes, I work in a language where junior developers and people deeply unaware of the language advocate anti-patterns and bad practice as matters of law, often for personal defensive reasons. Its hard to not feel patronized. You are correct in that I do not know you, but I have been doing this work long enough to see when people hide behind abstractions they don't understand as necessary to mask their level of confidence and then argue from for best practices from that perspective.

My best possible free advise: only advocate to what you practice. If, for example, you have never written an application in JavaScript without a framework, such as Angular, then you are an Angular developer not a JavaScript developer. If you speak to something you have never practiced with a presence of authority people with 10, 15, or 20 years experience will be condescending. That is why imposter syndrome is a thing. Its better to get the unexpected honesty from some irrelevant guy online than get hired into a job and either get it in person or worse compensating for a manager with imposter syndrome.

Re: TypeScript is surprisingly ok for compilers

#192

TypeScript is an incredible language in general. The fact that Functions are Objects that can have properties/methods is supremely undervalued. Are there other languages that do this so nicely? It's the perfect blend of OO and functional. Programming is mostly about gradually figuring out the right design I find. JS/TS let's me evolve things naturally without big rewrites. function foo() {} function bar() {} function…

This is a Javascript feature, not really a typescript thing. You can do the same thing with python

Re: TypeScript is surprisingly ok for compilers

#193

TypeScript is an incredible language in general. The fact that Functions are Objects that can have properties/methods is supremely undervalued. Are there other languages that do this so nicely? It's the perfect blend of OO and functional. Programming is mostly about gradually figuring out the right design I find. JS/TS let's me evolve things naturally without big rewrites. function foo() {} function bar() {} function…

This blend of functional and oo programming was pioneered by scala.

Lisp of course supported both decades earlier though :)

Re: TypeScript is surprisingly ok for compilers

#194

Earlier quoted context omitted.

FP in python is painful without tail call elimination and the higher-order function syntax is so clunky

JS also doesn't have TCE, but for Python even just the lambda limitations are surprisingly annoying. I can't tell you how many times i've been frustrated because it's nearly impossible to put a print statement into a python lambda

That's a mismatch between Python's choice of lambda syntax and the use of whitespace instead of curly braces.

Re: TypeScript is surprisingly ok for compilers

#195

Earlier quoted context omitted.

The fact that Functions are Objects that can have properties/methods is supremely undervalued. Are there other languages that do this so nicely? It's the perfect blend of OO and functional. Yes. C#. The equivalent are `Func` and `Action` types representing functions with a return and without a return. In fact, the JavaScript lambda expression looks awfully familiar to C#. One of the snippets below is C# and the other…

this doesn't really address OP's point, where in JS you can do: const foo = () => doSomething; foo.help = "this is a description of the function"; const commands = [foo]; // print help commands.forEach(c => console.log(c.name, c.help || "No help is available for this function"); Presumably this isn't possible in C# because it's statically typed, so the object returned by "() => doSomething" can't be converted into on…

It can.

.NET/C# has a `dynamic` type (aka `ExpandoObject`). That would be one way to do it (but would require casting to invoke). It's not exactly the same since you'd assign the `Func`/`Action` to a property of the `dynamic`. `dynamic` is generally avoided due to how easy it is to get into a pickle with it and also performance issues.

An alternate in this case is probably to return a tuple which I think is just as good/better.

Example:

    var log = (object message) => Console.WriteLine(message);
    var foo = () => log("Hello, World");
    var fn1 = (foo, "This is the help text");

    var commands = new[] { fn1 };
    commands.ToList().ForEach(c => {
      var (fn, help) = c;
      log(fn.Method.Name);
      log(help ?? "No help is available for this function");
    });
https://dotnetfiddle.net/szxb9F

The tuple can also take named properties like this:

    var log = (object message) => Console.WriteLine(message);
    var foo = () => log("Hello, World"); 
    
    var commands = new (Action fn, string? help)[] { 
      (foo, "This is the help text"), 
      (foo, null) 
    };
    
    commands.ToList().ForEach(c => {
      log(c.fn.Method.Name);
      log(c.help ?? "No help is available for this function");
    });
https://dotnetfiddle.net/oPK1d8

Alternatively, use anonymous types:

    var log = (object message) => Console.WriteLine(message);
    var foo1 = () => log("Hello, World");
    var foo2 = () => log("Hello, Neighbor");
    
    var bar = new[] {
      new {
        doSomething = foo1,
        help = "This is foo1's help text"
      },
      new {
        doSomething = foo2,
        help = "This is foo2's help text"
      },   
    };
    
    bar.ToList().ForEach(b => {
      var (fn, help) = (b.doSomething, b.help);
      fn();
      log(help);
    });
https://dotnetfiddle.net/KyBtgZ

The next release of C# (12) will include named tuple types: https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...

Very much looking forward to this since it gives you a lot of the same power of the JavaScript map/TS `Record`.

    > ...because it's statically typed
While this is true, the `dynamic`/`ExpandoObject` is an oddity and lets you do weird things like multiple dispatch on .NET (https://charliedigital.com/2009/05/28/visitor-pattern-in-c-4...). But C# has a bunch of compiler tricks with regards to anonymous types that can mimic JS objects to some extent. The tuple type is probably a better choice in most cases, however.

Re: TypeScript is surprisingly ok for compilers

#196

TypeScript is an incredible language in general. The fact that Functions are Objects that can have properties/methods is supremely undervalued. Are there other languages that do this so nicely? It's the perfect blend of OO and functional. Programming is mostly about gradually figuring out the right design I find. JS/TS let's me evolve things naturally without big rewrites. function foo() {} function bar() {} function…

If you take out all the “script” legacy (type coercion which was common for scripting languages when JS came out, the initial lack of a module system which led to all kinds of hacks, the scope of var declaration, etc), JavaScript and its prototype based approach is really good.

In fact I wish that constructor functions, and the class keyword never existed.

You can do the same with Object.create and a function closure, isn’t more verbose and it fits better with the mixed functional/oop approach of the language.

Re: TypeScript is surprisingly ok for compilers

#197

To OP: You could avoid the visitor by using an IIFE style switch using the run utility fn: export const run = (f: () => T): T => f(); Now you can go: const inferred_type = run(() => { switch(blah) { ... } })

You don't even need to do this much, you can just invoke the function and let the return type be inferred.

  const inferred = (() => "Hello")() // Inferred as "string"

If you really don't want to use an IIFE because you don't like the "()" at the end, you can just:

  const myFn = () => { switch(...) }
  const inferred = myFn()

Re: TypeScript is surprisingly ok for compilers

#198

It sure is. For anyone looking into Compilers and just starting out, I recommend this book: https://keleshev.com/compiling-to-assembly-from-scratch/ The author uses a TypeScript subset to write a compiler to 32bit ARM assembly and explains that it almost looks like Pseudocode, so it is very accessible. A sentiment I can get behind, despite avoiding it in any case possible.

This looks great -- thank you for sharing!

Re: TypeScript is surprisingly ok for compilers

#199
post #107
post #53

Earlier quoted context omitted.

I haven't used it in a couple of years (tbh I may have to remove "full stack" and "Angular" from my CV...) but I don't recall TS compilation being particularly slow. Are people not happy with how quick it is, or do you have a particularly big/complex application you're working with?

Notion is more than 10k typescript files and we view typecheck slowness and memory pressure as an existential threat to our codebase. Right now our typecheck needs ~12GB of heap size but the memory needs have accelerated recently.

Can you not split the 10k files into modules for incremental/parallel compilation?

Re: TypeScript is surprisingly ok for compilers

#200
post #140

Earlier quoted context omitted.

>>> Are there other languages that do this so nicely? It's the perfect blend of OO and functional. Python, where everything is an object.

In Python, can typings define a property added to a function? Example, I have some Redux helpers that are functions, but those functions also define a `.actionType` property. TypeScript handles that. edit: accidentally wrote "object" instead of "function"

The typical approach to this in Python is to define a callable class instead. If you define the __call__() method on a class, instances of the class will be callable.

  class IntAdder:

      def __init__(self, x: int) -> None:
          self.x = x

      def __call__(self, y: int) -> int:
          return self.x + y

      def __str__(self) -> str:
          return f"({self.x} + ??)"

  add1 = IntAdder(1)
  assert add1(3) == 4
  print(add1)
  # (1 + ??)
As mentioned in the sibling comment, you can define a Protocol which is analogous to an interface, so if you had a protocol like this:

  from typing import Protocol, TypeVar

  T = TypeVar("T")

  class ValueUpdater(Protocol[T]):
      def __call__(self, y: T) -> T: ...
Then IntAdder would be considered a subclass of ValueUpdater[int] by the type checker. Demo: https://mypy-play.net/?mypy=1.5.1&python=3.11&flags=strict&g...
Post reply on HN