TypeScript 5.0
devblogs.microsoft.com
devblogs.microsoft.com
The top thing listed in this release (TypeScript doesn't follow semver, btw) is about Decorators. I find the whole story about Angular's role in TypeScript early days to be very fascinating because I don't hear people talk about it anymore (just search "AtScript TypeScript" if you weren't around at the time). It was the Angular team that forced Decorators to be added when it was still stage 0. In exchange, they forfeited continued work on their would-be competitor to TypeScript.
Even without the Decorators thing, Angular was intensely popular and it made a big impact how they went "all in" on TypeScript, pushing a lot of early adoption. I know lots of people that first started with TypeScript because of work on an Angular project.
I think a lot of people don't seem to know/remember how touch-and-go TypeScript was in the very early days. There were many large projects that were all-in on FlowType, and others still that were pushing for Elm, etc. For example, it took quite a while for you to be able to do JSX _at all_.
Today, we just have TypeScript. Well. I do know one company that uses ReasonML (or isn't it called Rescript now?)
---
Historical stuff aside, I'm extremely happy we ended up with TypeScript over the others because the team is so incredibly awesome and dedicated. It's rare you see such a large project so well shepherded by such a talented set of individuals. It speaks volumes that the average tenure on that team is so high. We've seen some public apologies from the Flow team on this topic so I don't feel like I'm talking behind anyone's back if I say they ended up truly not being up to the task of being what TypeScript is today.
- Flow has more adoption (it did, for a while, in the OSS sphere)
- Microsoft is evil (remember, this was before everyone was using VS Code and loving it. (Also, tautologically, TypeScript has been one of the biggest things that changed this public perception for the people I hang around))
- Facebook is awesome (oh, how times have changed...)
- Flow has total type soundness as a goal (from the beginning, and through to today, TypeScript still lists this as an explicit non-goal)
- You literally cannot use React and Flow together (it didn't support JSX for what felt like an eternity and Flow did from the beginning (I think?).
- Flow had exact object types (TypeScript _sorta_ has this today, but most people don't know to turn it on because it isn't in the strict-mode family: exactOptionalPropertyTypes)
- Flow had more features (and was faster)
- DefinitelyTyped didn't exist yet, and it was easier to find types for Flow (but, let's be real, both had nearly nothing compared to today)
For example, array bounds are not considered. Flow considers this program to have no errors, but TypeScript (with the correct option enabled) will:
let m = [1, 2, 3];
console.log(m[4].toFixed());
Also, DefinitelyTyped itself launched before Flow (2012 vs 2015), so the timeline on that point isn't right.> https://flow.org/en/docs/lang/types-and-expressions/
That's what I was talking about re: Flow.
That's a really insightful comment you make about the "turn of the phrase" between how the two marketed themselves. Super interesting stuff.
also, apologies for messing up the timeline on the DT repo. My memory failed me there. Has it been that long?!?
It's unfortunate that people have, over the years, decided that just being upfront about this fact means that TypeScript has a vastly different prioritization of soundness than Flow. We don't; both checkers use soundness as the default assumption when designing behavior.
However, keeping up with the constant breaking changes (I helped maintained a few complex flow typedefs) led to me getting disenchanted and burnt out with Flow.
Also, at one point a change was introduced where most (or all) internal errors would just cause a type to decay into `any`s, which frustrated me a lot.
I don't hold it against Flow though; its only customer is the internal React team, and it's a 0.x software too.
We've migrated our code to TypeScript later and it was a bit smoother sailing (although the typedefs for a few popular react ecosystem libraries were just... Abysmally wrong, it didn't matter at the end of the day; it was still easier).
The main reason we switched was the tooling. The language server was slow in the best of times, would crash constantly, would memory-leak all over the place. Some of our devs stopped running it at all because it was so broken all the time. Then I tried out TypeScript and the speed and stability were breathtaking, and we never looked back.
EDIT: oh, also as someone else mentioned it was a React project, so I'm sure that played a part.
About a year later typescript got strict null checks and discriminated unions, and from that point on typescript just kept improving, the community type defintiions kept getting better, and flow felt like it was stagnating and had lots of performance issues (esp on windows machines).
Flow actually still has a few notable features that typescript still lacks but are often asked for. For example, flow as `Exact` types that ensures that an object doesn't have excess properties throughout its lifetime - ergonomics are a bit awkward though.
Branding doesn't really enforce anything except what the user asserts is the case. Its not the same thing.
* first class opaque type support
* exact object type
* correct variance, sound liskov oop
* no transpilation support (/*: */ and /*:: */) - so simple, so powerful; jsdoc ts doesn't compare, you can't import type star, when consuming libraries you have to increase maxNodeModuleJsDepth and other shenanigans; in flow you simply have access to all flow type language; why they don't want to do the same with ts is beyond me, it's like half a day of work to do it?
* nominal types for classes, structural for the rest - as it should be
* correct spread matching runtime behaviour
Flow is under active development. They recently completed ~2 years of work on local type inference which is a big deal. But dev team is not interested in external contributions - quite opposite to how ts development is done.
I did switch to ts as well but do miss above.
Related to your point on supporting 0-transpilation workflows as a first class citizen, is the fact that Flow was explicitly just type annotations & checking, and aimed to introduce 0 runtime constructs.
This is something Flow did from the beginning and TypeScript eventually established as a non-goal after already implementing several runtime constructs that they can no longer afford to remove for backwards compat [1].
Though interestingly enough, Flow themselves recently announced they're going to start introducing runtime constructs, which is an interesting plot twist [2].
[1] https://github.com/Microsoft/TypeScript/wiki/TypeScript-Desi...
[2] https://medium.com/flow-type/clarity-on-flows-direction-and-...
https://devblogs.microsoft.com/typescript/a-proposal-for-typ...
I went with TypeScript early on because the compiler chain felt better integrated than the alternatives. No messing with chains of babel translators and source mappings; just use one tool. Maybe I liked the syntax better, also. Although as I recall, in the beginning, somebody my company interviewed had set up TypeScript using Babel, and it was all very over-my-head and impressive. He turned out to be too good to work for us, but some of his ideas really stuck with me.
[1]This is why I dislike cutesy names for software projects. Just call it FacebookTypeAnnotatedJavaScriptFrobulator3003 (FTAJSF3003) or something.
I actually think the bigger driver for TypeScript was Anders' history of working on C# and Delphi before that.
What caused you to choose Flow over TypeScript?
Even well after TS was clearly the better option (as in 2022) the twitter web team opposed anything being done in Typescript like separate modules that would be a dependency of the web repo.
At least you recognize the better direction now.
I had a hard time convincing a couple of places I worked to use TS rather than Flow for greenfield projects, but I’d tried them both out and concluded Flow just felt too unstable - the server would consume all my memory and crash and it just didn’t feel like a good dev experience. I managed to convince them by showing them how you could strip out Typescript types in much the same way as Flow if TS did turn out to be a dead end. I also recall having vigorous debates at React meetups where I was the only person in favour of TS haha.
How times changed - you definitely can’t be blamed for choosing Flow at the time though as TS was the outsider. Also MS weren’t such a trusted brand for developers, people still associated them with proprietary stuff like .net/full fat Visual Studio and I think a few people had burned out in the MS ecosystem before and didn’t want to touch their stuff again!
I put quite some time into evaluating Flow vs Typescript around 2016, and preferred Flow mostly because its type checking was more correct, and its bugs more straightforward. Typescript would happily compile all sorts of incorrect code even with its strictest configs, it was insane.
I eventually found my happy place with Scala.js.
If Flowtype had more resources from Facebook it could still be the dominating language
From the outside, it seemed a fantastic example of collaboration between two separate (competing?) teams. It took humility and pragmatism for the Angular team to abandon AtScript and recognise TS as the better long-term bet.
The only other context I'll add is for people shipping Flow that I knew at the time they felt that this announcement felt like it came about two years too late. I had already switched to TypeScript long before because, in part, of the things they're apologizing for in that article which were evident long before being said out loud. I say that with great reverence and respect for the people that worked so hard on Flow, by the way, but that's the situation I experienced.
- Yarn
- Jest
- Luxon
- Gatsby
- Expo
- Styled-Components
- GitKraken
- GraphQL-js
and that's just off the top of my head. I'm sure there were many more.
In the very early days (in every circle I was in) Flow was ahead by every measure (known examples, excitement, adoption, features, speed, etc). You could point to real live running apps like GitKraken and Discord (hopefully my memory isn't failing me on those) that where shipping Flow very early. And you could use JSX! At the time there was literally no known project (especially OSS) actually shipping TypeScript. Not from Microsoft and not from anyone else. It was hard to tell if TypeScript was more of "embrace extend extinguish" (obviously with hindsight we can be absolutely certain that it wasn't that (unless we're talking about a decades long "long con" lol))
But there's something I could never have anticipated at the time that's more important to me today than any feature of the language:
The TypeScript team have done a breathtakingly amazing job of carrying the project through the years. TypeScript, as an open source project, is an absolute triumph: and I think it has everything to do with the people behind it.
At this point TypeScript is "good enough" in every way that really matters. If they consciously stopped developing the language and just focused on performance and bugs I think we should all call that a success. I really believe it's been handled _that_ well.
Meanwhile Flow went the other direction and there were bugs (in the 0.30 era, approximately) that had people pulling their hair out that were caused by the impedance mismatch of them making it for Facebook first and the rest of the world last. As far as I can tell, this really never changed (or at least, if it did, then maybe it was "too little too late").
Meanwhile, it seems like TypeScript has been managed with the literal opposite mindset: putting us in a situation where only one major project is left using Flow... React.
There are other projects like ESLint that have been... how do I say this in a not bridge-burn-y way... surprisingly reluctant to realize that TypeScript isn't some passing fad. But I'm confident that they're going to have their wakeup call sooner or later. The culture of JavaScript-land is just not loyal enough for gatekeeping a technology like TypeScript. Look at webpack. We all spent nights and weekends for years gaining knowledge on how it works and weeks per year getting familiar with it, then esbuild happened and we threw webpack away overnight like it never even happened. I believe the same fate awaits projects that deny the necessity of writing in TypeScript at this point in history, with the possible singular exception of React.
Wasm is a cpu or low level operating system and not programming language
[1] https://github.com/rustwasm/wasm-bindgen/tree/main/crates/we...
Still pushing for it. TS is like make-up on a pig, compared to Elm.
> I do know one company that uses ReasonML (or isn't it called Rescript now?)
Re* is also a better alternative imho. Better interop with JS/TS is very nice. But in place one could use Elm, I'd say it certainly wins in the "clean" reward.
Too foreign to frontend audiences? It has a lot of fans in flutter
One company outside Meta?
https://rescript-lang.org has a list too
Typescript was started at Microsoft by the guy who designed Turbo Pascal and C#, so completely independently from Google's Angular team. Angular had its own "AtScript" and eventually ditched that. Typescript had experimental decorator support well before Angular Team moved from AtScript, because it was a ECMAScript proposal.
Angular had zero influence in the design or success of Typescript. Typescript however does support JSX optionally so one can claim that React DID influence Typescript's design decisions.
I have personally never been one of those mega Microsoft haters but I witnessed shouting matches in the office from people that we're hotly opposed to TypeScript being added to the codebase against others using Angular as a core motivation in many of their counter-arguments.
I'm super glad we have TypeScript one way or the other because the team is so dedicated to OSS.
Angular.js was huge, by the time Angular version whatever because it was always changing, figured out what it wanted to be, most front-end developers already moved to React.
What Microsoft product uses Angular? Doesn't Teams uses Angular.js but not Angular? and what does a Google conference has to do with Microsoft? Nothing.
Do you have a source for this. My memory isn't so good but I seem to remember that the Angular team pushed to get this Stage 0 proposal implemented even though the TypeScript team usually waits until Stage 2 or 3 to implement.
While it's true that TS would have been started with or without Angular, I think OP is largely correct in the influence that Angular's embrace of TS had in TS's long-term success.
It's difficult to see these days, but if you were watching TypeScript's adoption numbers back when Angular made its TypeScript announcement, there is a marked inflection point when that happened. I was running lots of charts and graphs at the time tracking all kinds of data, and in every graph, you could see the Angular announcement in the chart; it's where the line went from kinda slow and linear to kinda fast and exponential. It was a true discontinuity in the second derivative.
We can't run history twice and see what would have happened without Angular, but I think the quantitative impact in this timeline is undeniable.
Talk excerpt talking about Angular directives ~8 years ago! https://youtu.be/lGdnh8QSPPk?t=275
Ironically, I think that angular is the framework that benefits least from actually using TypeScript. There is a separate templating language that's only type-checked if you set the right compiler options. JSX is much better suited for that. Being OOP like angular, it often requires opting out of null-safety or init-checks, because something is late-initialized. Having mutable instance state results in less opportunities to be more strict with typing.
Its good that the TS team decided to align with the ES standards. Initially (talking like v0.8.0), I had the impression that they're building a "C# for the web", being incompatible with ES. Maybe that's why enums and namespaces were added and initially, the boolean was named bool.
What's today called "namespaces" in Typescript was originally called "modules" and then "inner modules" (to differentiate from "exterior modules") and is a tiny simplification on a JS pattern that was extremely common at the time of Typescript's inception called at the time "IIFE modules". "namespace" is a very C# name chosen in desperation (when it became clear that "exterior modules" were the present not just the future of the language and "interior modules" was too confusing a term to live), but it's a very old (and used to be extremely common) JS pattern that TS gave a tiny bit of syntax sugar to. It was a "standard" that existed at the time that was (rightfully) killed by AMD/UMD/CommonJS/ESM, but it is hard to fault the Typescript team at the early 0.x days thinking the "Stage Wild" JS pattern would possibly live on for many years to come. (This is also relevant to the patch notes for Typescript 5.0 as 5.0 is the first version [!] to itself be written as [proper/"exterior"] modules rather than namespaces. There are some interesting stories, including in these release notes for why that took so long to transition and what the performance benefits have been post-transition.)
Even those things that didn't seem like ES standards have some history as JS "standards". It's not like TS 0.x/1.x didn't support "standards", it is more that the TS team mostly decided to focus more on later stage ES standards (more likely to be accepted by browsers) rather than trying to "prollyfill" Stage 0 and "Stage Wild" standards.
Just like without Rails framework, we may very well not have Ruby today.
Also, without WordPress, we may very well not have PHP today.
My understanding is it should allow you to finally have TypeScript files that import other TypeScript files and include the file extension. This is important because, for one, it means Deno TypeScript modules and non-Deno TypeScript modules are now compatible (can import each other)! As long as no unavailable system APIs are used, of course
This has been a problem in a project I've been working on where a Deno back-end service wants to share some code with a Next.js front-end service. Currently, the shared modules are not able to import anything else, because Deno requires file extensions in import paths and non-Deno TS requires no file extensions in import paths
> New compiler options
> - allowImportingTsExtensions: Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set.
To be clear, I'm not using tsc to build code for Deno. I've got module X which imports module Y, neither of which have any platform-specific dependencies. Right now if module X imports Y with the .ts extension, Deno can import X but tsc can't. If module X imports Y without the .ts extension, tsc can import X but Deno can't. With this compiler option, I should be able to include the .ts extension and allow both to (independently) import the same code
Namely, I have an Nx monorepo full of standard TypeScript code, but that code works with a many things: Node, Electron, frontend apps with Angular or Svelte or whatever, etc.
I want to use Deno for some new stuff, but Deno couldn't import any of that code without modifying that code so it no longer worked with all the non-Deno stuff.
For a quick test, I made a new default Nx monorepo and a regular TS library and a Deno library and a Deno app.
I changed all imports to use '.ts', and added this to the tsconfig.json:
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
...et voila! My Deno code can finally import all that normal TypeScript code I have sitting around.Haven't tested anything else yet, so I am not sure what, if any, issues those two changes above, plus including the .ts extension, might cause for other existing TypeScript projects.
It's weird to see this:
> commentary in the PR about this new mode being "definitely not suitable for Deno"
I wonder what they meant by that. I mean, this doesn't magically make all TS code Deno-compatible, but nobody expects it to. What it does do is remove by far the most ubiquitous (and silly) barrier to TS code being Deno-compatible. There are others- system APIs, http imports. But this change allows a whole lot of code that doesn't use those to become compatible
I don't think he is talking about the problem we are, which is that because Deno requires the .ts extension, Deno doesn't actually work with standard, non-Deno TypeScript code (that imports other standard TypeScript code).
I mean, until now.
I will run some more extensive tests tomorrow or on the weekend, and maybe go comment there if I have something useful to say.
But anyway, it seems to me that if, like me, your problem was "Oh no, I cannot import my code into Deno because I cannot add the '.ts' to my imports without breaking it in other TypeScript use cases" then that problem is solved in TypeScript 5.
I have the same exact problem at work, except the monorepo is bigger and there are a lot of people who might not be excited to change all their import statements just so my own experimental Deno tools can use their code but... step by step. This seems like a big step for my personal TypeScript projects. :-D
[1]: https://github.com/microsoft/TypeScript/pull/51669#issuecomm...
FWIW I've been using version 5.0.0-dev.20230223 for a few weeks specifically for this feature - to share code between TS Vite/web and Deno projects - and it's been working without issue.
Personally, I found all the `npm` integration stuff to be a bit overkill for what we were looking for, and honestly Deno's network requests while installing from npm were constantly flaking out in our CI. We ended up just disabling it via Deno's `--no-npm` flag (https://github.com/denoland/deno/issues/17916) and reverting back to a simple set of import_maps to get the node deps we needed. Works like a charm!
Feel free to reference if it's useful:
I recently tried to modularize some code into a package that used Typescript import-path aliases. I don't know which step(s) I got wrong since there's multiple tools/packages, each with different versions, each with a different package needed for the appropriate build tool (x-for-webpack, x-for-rollup, etc). When building and re-using the module in some other project with a different build config I couldn't get it to build properly and wanted to just get back to working on my actual project.
I eventually just went and looked at the typescript repo for a reference build config thinking they'd have something easy to follow, but I just decided since they don't use import path aliases I won't either.
I hope all the tools go away that require me to look up things like: "is it an X type of module? if so export/bundle it this way" or "are you using an X type of module? if so import it in Y fashion and use build-pipeline plugins A B and C"
If we could push JavaScript performance to be another order of magnitude faster it wouldn't be necessary to use other languages, imho. Of course, pushing it that far without effectively creating a new one would be difficult, to say the least.
Nothing is abandoned and in any case typically only a small set of libraries is needed which should be carefully picked.
Want structural/duck typing? No problem; that's the default. Define new interfaces that old classes happen to implement without having to wrap them. I always wanted that feature!
Want nominal types? No problem; just declare a field indicating the type name!
interface Square { classRef: "http://example.com/Shapes/Square"; width: number; }
interface Circle { classRef: "http://example.com/Shapes/Circle"; diameter: number; }
type Shape = Circle|Square;
(I like to express things in a way that can be easily translated to RDF, hence my use of URIs for type and attribute names)Since TypeScript types don't runtime checks, you can even do it on atomic types!
type USDollars = number & { [Symbol.for("http://ns.nuke24.net/Synx/unit")]: "USD" }
type CanadianDollars = number & { [Symbol.for("http://ns.nuke24.net/Synx/unit")]: "CAD" }
const someAmount : CanadianDollars = someExpressionReturningUsDollars; // Compile error! Try doing that in Java! I OFTEN WISH I COULDA pile of thoughts on the subject from back when I first came up with it: http://www.nuke24.net/plog/32.html
By comparison, JavaScript (and by extension, TypeScript) is still lacking fundamental features and the library ecosystem situation is pretty bad.
I wish there was a modern language that took all the good non-manual-memory-management things from Rust and added a GC and some immutable data structures. Error handling, enums, macros (with compile_error! / diagnostics API), traits / approach to OOP, embedded tests, doctests and the relentless determination to add examples in the docs in general... Everything in Rust feels like "oh, they got this right too", which hasn't been the case for any other typed lanuage I've used in the past 15 years (including typescript, my previous favorite; purescript; go; haskell)
I ask because I have never delved into C# only heard it's Microsoft's Java. And I am no fan of the original Java at all so C# gives me pause.
Speaking as someone who started with Java 1.2 and saw all the crap that happened to it.
C# is currently lightyears ahead of Java in every way, especially now that MS is not Micro$oft to people on the internet any more =)
Let’s not claim things that can’t be objectively proven. C# does have much more features than Java, but that is not necessarily a plus in case of a programming language. There are features that are definitely better, but I am not bought that the whole would be.
Plus, ecosystem-wise Java is much bigger and much more open-source. The runtime is also better on the JVM-side, though this is offset by C# expressing more low level details.
I've been doing C# on a MacBook with JetBrains Rider for years. Some code runs in Linux containers, some on AWS Lambda.
I rather do .NET than Java, but the FOSS story isn't as Microsoft sells it, hence why on our agency .NET is mostly used on Windows projects, and usually loses against Java or node in UNIX like RFP, even after .NET Core reboot, because of dependencies and existing enterprise tooling.
DI is almost always in web, but via constructor instead of annotations.
Similarly recent libraries such ASP.NET have been working hard to use more of these things to eliminate their own boilerplate. The latest ASP.NET templates use top-level statements and some global usings and are getting very lightweight in terms of starter-level code.
.NET does have annotations and dependency inversion, but those too tend to avoid boilerplate more than create it. Few annotations are "required", depending on your domain and which libraries you are expecting to use. .NET now has a single, mostly standardized dependency injector that almost everyone has agreed to use (Microsoft.Extensions.DependencyInjection) at this point. It intentionally only supports a bare minimum of Dependency Injection needs and is nothing like the Kitchen Sink approach of something like Java's Spring. (For instance, zero out of the box support for wiring Dependency Injection via XML files. .NET's DI is always code driven, often in a Startup.cs, Program.cs, App.cs, or Main.cs file.)
I've been increasingly finding in C# that I'm writing new code with zero templates and almost no snippets-expansion. (There will always be plenty of legacy code out there with much more verbosity, of course.)
The easiest suggestion is to try it for yourself. The `dotnet` tool is cross-platform, generally an easy install, and its `dotnet new` command will help you try many easy template types. You can relatively easily work entirely in VS Code today (as opposed to older versions of C# often "needed" the full bulky Visual Studio install for templates, language servers, and other stuff).
I do hope to try it maybe in recent future.
They had me at features, lost me at manual compilation ordering.
C# can fake algebraic data types in some ways/some cases. Though if you are expecting to do a lot of it you are still better off in F# or C#/F# hybrid projects. (F# of course being a proper ML-family language.)
Or in Scala, technically not an ML, but is as close as you'll get in a nominally typed language.
enum RGB:
case Red, Green, Blue
def log(x: RGB) = x match
case Red => print("red")
case Green => print("green")
// error, not exhaustive
Obviously Scala can do a lot more, including GADTs, which Rust will never have until HKTs are supported.Ton of powerful languages to choose from these days, good times...
It's my general purpose language. I also use Rust everywhere Kotlin isn't suitable.
Swift seems more in the Go or Java class, rather than being competitive with C/C++ like Rust is. If that's so, Swift is still appealing as a pretty-fast, safe language with a much more sophisticated type system than Go or Java. But... TypeScript is too!
I have a feeling in terms of raw performance, JS is probably closer to Swift than Swift is to Rust. The important difference between Swift and JS isn't performance as much as which platforms/APIs/languages they can integrate with.
(Maybe I'm underestimating Swift's performance, though, or overestimating JS -- corrections welcome)
I feel like the entire industry has had a "kneejerk reaction" to C++ and its abysmally slow compile times. Everyone jumped onto the interpreter bandwagon and ended up throwing the baby out with the bathwater.
It is definitely possible to have sub-second compile times for large, complex software! Just look at Jonathan Blow's Jai language. He can recompile and reload an entire 3D game engine in about that time.
We can have our cake and eat it to. We can have efficient, compiled languages and still have safety and fast compilation.
I can only think of Ruby and Python that use a strictly interpreter mode (in their most common runtime).
Java, C# use a hybrid solution, but for all practical purposes they are running as extremely efficient machine code, how is it not “efficient business language”?
But sure, though I don’t really buy the argument that JIT compilers would “severely limit” the type of optimizations - there is no significant performance difference - if any - between AOT compiled managed languages and JIT-compiled ones. Sure, there are more constraints in case of a JIT, but it’s not like going in the other direction and letting gcc/clang chew 10x time more on the same program would give you a significant speedup, if any. Speculations (which are not possible AOT) may even reverse the fields.
D, Haskell, OCaml, Go are all in the same ballpark as Java and C#, and even JS, hell, they may be better.
Imagine a language as easy to use as Python, with the strong typing of Typescript, but designed from the ground up to always be fully compiled and hence running as fast as C++, but with build times measured in fractions of a second... fast enough to feel interpreted.
This extra optimization is somewhat offset by the very point of a managed language: the programmer don’t want memory layout details to leak into the design/APIs, but in the rare case it is needed it can be done just as well with the escape hatches they provide (byte buffers, value types also bring you quite far). But business logic seldom involve these scorching hot loops to begin with, so there may not even be anything to optimize in this manner.
Or as others have said, F#, or maybe Scala. Or if you're feeling really brainy, Haskell.
But Rust was, in its early days, basically inspired by the ML type system, its type inference model, and its pattern matching facilities. The first Rust compiler was written in OCaml.
This basically describes all of the recent ML – perhaps more specifically OCaml – influenced languages like Kotlin, Swift, F#. (Rust is also heavily influenced by OCaml but its distinguishing feature is manual memory management with lifetimes.)
I do wish we had a good Linux/Posix option with as good of a package manager as Rust's cargo. Kotlin and Swift have some support but are largely focussed on the JVM and MacOS respectively. OCaml itself is of course an option here but its syntax and smaller ecosystem is a stumbling block. Reason is an attempt at a more familiar syntax for OCaml but that community is mostly focussed on transpilation to JavaScript with ReScript.
Here is another more subtle but important example: flexible API for error conversion, powerful language features and macros together enable the language, in conjunction with libraries like https://docs.rs/anyhow/latest/anyhow/ which gets you the best of all worlds in error handling: concise `?` operator for writing error handling code, eas to add additional message context (using `with_context` from anyhohw), differentiating between functions that can and cannot throw in the types (Result<T>), and the ability to get exception style backtraces from Result, too (that last one seems to be rare)
Another subtle QoL which is often overlooked when implementing macros: `compile_error!` (and soon even more powerful diagnostic API). With that, macros can report custom errors back to the programmer via the compiler and language service, rather than becoming an incomprehensible mess. For example, the peg parser macro will mark errors with infinite left-recursive rules that don't have caching set up with custom error messages.
Typescript types don't exist at run time, at all. So it's easy to be better when your language is merely about static analysis as it will not enforce any sort of type system during runtime. Java, Go or C++ have different constraints.
There are no types whatsoever as far as processors are concerned. No types in assembly Not for Go or Java, not for C, and not for Rust. All you gotta do is keep compiling.
I disagree, Javascript does have types and runtime type errors, just not all the ones Typescript compiler has, it makes Typescript extremely leaky as a Javascript abstraction. Typescript compiler cannot represent every single Javascript type combination either, it will would have to be a Javascript interpreter at first place.
Here's types existing at runtime: https://go.dev/play/p/rc--yVzJ9bt
And it would speed up the TypeScript Compiler.
My bet is:
TypeScript typechecker in Rust:
It's simply impossible to keep up with TS for competing compilers.
Node.js: https://nodejs.org/api/worker_threads.html
Browser: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers...
However, threads are very rarely needed. The common use case in other languages is I/O, and JS environments handle that with async I/O—a superior choice, IMO.
And the language and the VM has been, and will be for any foreseeable future, single-threaded.
Whatever it supports, Javascript-the-language has no concept of threads. And workers are basically external processes with a somewhat awkward event-based communication and certain limitations.
Whatever Deno uses internally to implement them has no bearing.
The big problem is the gap between TS and JS. User defined typeguards are a usable work around but it would be nice to be able to use a native isMyType function.
Also would be nice to have constraints natively in types. Like string lengths or max ints.
Arguably the highest quality TS lib out there.
Being able to generate types, encoders, decoders, apis, guards and even arbitrary data is extremely powerful.
I feel like the name could use a bit of work for a start! "schema" is way too generic.
- for functional programmers TS offers lots of flexibility and power many other languages including statically typed and pure don't
- TS functions or methods that throw don't show up in the type system (they do in Java)
I hope TS keeps getting stricter.
The type system is really nice, so even without being able to use the full range of JS hacks and escape hatches, I think it’d still be a nice language to work in.
Example: https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgTwLI...
In the example above, the problem is that typescript allows casting function types to omit optional arguments, and also allows using a function with n arguments as a value where a function with >n arguments is expected
> 5.0 is not a disruptive release, and everything you know is still applicable. While TypeScript 5.0 includes correctness changes and some deprecations for infrequently-used options, we believe most developers will have an upgrade experience similar to previous releases.
(Which is to say that Typescript probably couldn't use semver if it wanted to because it has some extreme views on backwards compatibility, but also that this amount of codebase churn is absolutely semver breaking in the strictest semver senses even if it is mostly backwards compatible.)
But yeah, they should just go ahead and follow semver from now on.
the typescript project continues to set the bar extremely high in terms of changelog and clear communication. love you so much, drosenwasser and co!!
> Decorators are an upcoming ECMAScript feature that allow us to customize classes and their members in a reusable way.
huh. i thought this was a bit early to do this but i checked (https://github.com/tc39/proposal-decorators) and looks like they've moved to stage 3. curious how this is going to change library/api design in the long term.
If you like them, you're probably already drowning in them. Me, personally, I could take them or leave them.
I don't think that changes with stage 3 decorators, unfortunately. It makes NestJS really error-prone, in my experience, and it's a big reason I stopped making tooling for NestJS projects.
In that case, they can remove all JS weirdness from it, simplify it, add a proper standard library, and add other good parts from other (especially functional) languages to it.
My wish list for such a language (in addition to what is already in Typescript), in no particular order:
- Generic object literals (Why should generic type inference be limited to functions?)
- Deep support for an alternative to exceptions using a Failable<TResult, TError> type
- Localizable keywords (Why should programming languages be tools of cultural hegemony?)
- Dependent types, with no real distinction between values and types (At a certain point, Typescript’s type system begins to look like a separate Turing-complete language within a language. It’s probably time to do away with this dichotomy entirely somehow)
- Higher-kinded types (This is a pending issue in TS since 2014)
- JSX built-in without the need for any React-like dependency (No need to use it if you don’t like it; in the general sense, it’s just syntactic sugar for composing function invocations)
- No return necessary (the last expression in a block is returned). Thus every flow control construct _can_ (but does not have to) be an expression.
- No null, undefined, or any of all that, in favor of using a Maybe<T> type
- Proper decimal types (it’s shameful for a language to be without it now)
- A reasonably extensive standard library (Math, Stats, Collections (pull & push), String, Objects, Date/Time, Async, Functional, DOM, etc.)
That would be getting close to the perfect language for me.
I don't think Microsoft are the reason why JS uses UTF-16 strings.
Is there a good library for this currently?
I've been looking for one and a Maybe library. The Maybe one I use is pretty small.
Have you tried Scala.js? It's pretty much what you're asking for - a first-class functional language with all the things you'd expect from that, with compile-to-JS as something that works and feels fully first-class (and good integration with TypeScript types via ScalablyTyped).
I look forward to the day when we support 5.0 as our minimum version and replace all of them with `const` generics for 1:1-inferred definitions like this:
const package = type({ name: "string", "version?": "number" })
Plus we’ll finally be able to remove the crazy hack we had to write to allow ts-morph to make type assertions on our codebase by transforming all of our `.ts` imports to `.js` in a virtual file system, which now that I think of it I’m probably looking forward to deleting even more XD
Great work, and looking forward to what comes next!
Felt a bit like the wait for a const generics in Rust (except here, it didn't take long at all)!
I typically dislike decorators because they are spooky action at a distance, and whenever I look at code in a language that has decorators, the code almost becomes a DSL of sorts.
Not that HoF and HoC don't tend towards the same problems, React used to be famous for how often HoC got used in the ecosystem and the confusion that caused!
Decorators are syntactic sugar for higher ordered functions. They fundamentally have the same capability, just with better ergonomics.
As such, you could write a function that takes in as an argument a class, and return a new class definition that extends the argument you provided... Or any number of other dubious practices.
@GET("/users/{id}")
function loadUser(id: int): Promise<User> {}
@PUT("/users/{id}")
function updateUser(id: int, user: User): Promise<User> {}That is TS, not Java. Not sure why the gp is calling it Java.
path("/api", () -> {
before("/*", (q, a) -> log.info("Received api call"));
path("/email", () -> {
post("/add", EmailApi.addEmail);
put("/change", EmailApi.changeEmail);
delete("/remove", EmailApi.deleteEmail);
});
path("/username", () -> {
post("/add", UserApi.addUsername);
put("/change", UserApi.changeUsername);
delete("/remove", UserApi.deleteUsername);
});
});
All your endpoints concisely and composibly mapped out in code, and not smeared across dozens or hundreds of methods and classes. Not an annotation in sight; just plain old Java.Shorter code is not always better code
For mature projects with experienced, cohesive teams, that’s a good thing. You want a DSL that blends right in with your fully capable base language.
But yeah, just like with any powerful feature, people can get excited and carried away.
Yes, decorators are not evil by themselves, but they allow people to make poor choices easier. Having to debug decorators, fiddling with order of execution + scope binding/closures when setting multiple decorators, can (not sure!) become a nightmare; depending on the code base. Or we just go straight to the hibernate spaghetti. Imagining having to use three decorators with the same name, but different functions, makes me not to want to work with this.
Having worked with (old) Java EE and Jakarta code bases, I've seen decorators being abused in 300 ways and breaking ABI in 600 ways, so let's hope we stay sane this time.
Not saying it's your case, but I noticed that a lot of people who hate TS like to use techniques and patterns that are usually considered bad practices, which often trigger errors in TS. Mutating an object to add a new property, mutating an array to add an element of a different type, processing apples and oranges in the same function without using generics or the correct union type, etc. Code works but TS doesn't like it and forces them to rewrite it properly and it feels like a hassle with no benefits.
I also noticed that lot of people who don't like TS think they need to type everything (every variable, every function's return... which is obviously inconvenient) instead of relying on types inference. There is usually very little to type in TS (compared to Java or C# for example). The two main things are the parameters of your named functions and your external data (i.e. the fetch responses). Almost everything else can be inferred.
I also observed that some people refuse to use VSCode (or any code editor with a good TS support). So they don't see any of the benefits while coding and think it's totally useless.
Not sure, people who like TS are usually for large corporate projects with OOP background. Most functional lispish type developer would be fine just using ES6 and above.
That said, I absolutely love TypeScript, even just for small personal projects. The value I get from VSCode typeahead, and being able to look up the expected fields on, for example, parameters or return values of a function is invaluable, never mind its power in refactoring.
I guess I would recommend that, if in the beginning, you feel a bit overwhelmed by TS and can't yet see its value, just give it some time. At least, that's what happened to me.
For me, I was out of the JavaScript cinematic universe for a long time (from about 2011 to 2018) and TypeScript was my entree back in. What got me deeply into it, and has kept me there, is not that it's better than JavaScript, but that, for my purposes, it's better than my at-the-time common languages: Ruby, Java, and C#. It gives me most of the linguistic flexibility that I'm used to with Ruby, while preventing me from dealing with the worst thing about it (Other People's Ruby being high on my list of terrible things). At the same time, it provides a level of "fall into the pit of success" structure around the type system that's superior to Java or C#, while not being as difficult to access as Rust can be.
(I like Rust, too! But the level of experience and skill necessary for somebody to be a "TypeScript operator" remains low, while letting those folks leverage really nice tooling built by folks like me who write TypeScript tools and libraries.)
Personally I wish either Rescript or Purescript gained adoption instead.
If we remove the "sensible" requirement:
type NonEmptyArray = [any, ...any[]] type NonEmptyArray = [unknown, ...unknown[]];
const nea: NonEmptyArray = [];
// ^^^ Type '[]' is not assignable to type 'NonEmptyArray'.
// Source has 0 element(s) but target requires 1. type NonEmptyArray<T> = [T, ...T[]];arr.filter(a => a.kind === „bar“).map(a => /* a should now be of type Bar just like in a branch */)
docs: https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...
``` arr.filter((a: A): a is A & { kind: 'bar'} => a.kind === 'bar') ```
If you define:
``` function isKind<K extends A['kind']>(kind: K): (a: A) => a is A & { kind: K } { return (a): a is A & { kind: K } => a.kind === kind; } ```
Then you can write:
``` arr.filter(isKind('bar')) ```
and get a properly narrowed return type array
The rate of innovation from them is really impressive.
Fantastic to finally see Decorators shed their "experimental" label (they've been the stable backbone of Angular for years).
They don't have the same features. The new one are based on the upcoming EcmaScript decorators.
> Note that the ECMAScript decorator spec now supported in TS 5 doesn't support decorating method arguments, unlike the experimental decorators TS has had an that Angular uses e.g. @Inject, @Self, @Optional etc. I'm guessing that this is part of the motivation behind the inject() function, where you can pass flags to it as a second argument to support cases like self or optional - it gives them a path to moving to the new-style decorators in the long-term.
AFAIK argument decorators are only used for constructors, and that usage can be replaced by using inject() with flags, so a migration would be possible even today - although I'm sure there would be plenty of as-yet uncovered subtle implementation quirks!
The obvious headache TS 5 will introduce is that failing to follow a decorator name with () will now attempt to treat e.g. Inject as a new-style decorator and cause a type error of some kind, which is likely to be confusing. I'm guessing the Angular compiler will have to do something to manage this, even if it's just ensuring there's a useful error message.
Do you know what caused the typescript team to make it a major release? Has the decorator api changed sufficiently to become a breaking change?
Then, a new error about the deprecations of ancient options to be removed in 5.5: https://github.com/microsoft/TypeScript/issues/51909
> TypeScript 5.0 has a minimum version requirement of at least Node.js 12.20 and later
https://devblogs.microsoft.com/typescript/announcing-typescr...
(I've done crazy things like use emoji named types in string unions and then used F2 to rename refactor them to a different emoji or name and not needed to worry if it missed any emoji literals.)
The only thing missing from both string enums and string unions is something to support [Symbol.iterator]() to iterate through the available options, but at this point I find that easier to write DRY with string union types (especially with typeof/keyof meta-magic) rather than string enums.
https://devblogs.microsoft.com/typescript/announcing-typescr...
A bunch of stuff had to be built to support good tooling in vscode for types with JavaScript, and that was leveraged for jsdoc also.
I don't use typescript, but I benefit from it in multiple ways, js doc and the occasional .d.ts file have made my life better.
That's my point.
I don't write typescript, but it has done wonders for the jsdoc ecosystem.
The only other argument being “no compile step” which is a non-argument in the age of modern bundlers.
TS also lets you do what Babel is for, translate the JS to earlier versions of JS. However, that has nothing to do with TypeScript itself, if your target runtimes support all the ECMAscript features you use you don't need to transpile, you only need to remove the type annotations, none of which are code (apart from the leftovers from early days mentioned above).
So you would need to complain about ECMAscript. The decorators in this release, for example, are there because it moved to a stage 3 ECMAscript proposal last year, which means TypeScript must implement it now - because TS ECMAscript and not its own language. So they need to support all of at least stage 3 proposals of ECMAscript.
Basically, Is this following pattern still possible?
<script src="cdn/typescript.js"></script>
<script src="mycode.ts"></script>
If not, what typed language do people here use for buildless front-end dev? I REALLY want to move away from weak-dynamically-typed PLs.https://www.typescriptlang.org/docs/handbook/jsdoc-supported...
I’ve never written TypeScript myself so just a guess.
There’s also this for node.js:
If this is what you're looking for, you aren't going to get it with TypeScript, even if you could parse it in the browser. It might be possible to port or build a TypeScript parser that runs in the browser (it might even be done already) but this would mean sending a LOT of code over the wire for something that was designed as a static analysis tool.
You can use runtime validation libraries like https://zod.dev/.
JS will eventually include its own type system so that you will be able to write typed code and have it run in the browser. However, even then the types won't be checked at runtime. You'll still have to rely on a tool like `tsc` to type check your code.
Does anyone know if the new package.json resolution settings can help resolve these issues?
The price for doing so is to turn off code generation, so TSC is only used for type-checking. But that’s the best way to use TSC anyway!
https://github.com/microsoft/TypeScript/issues/21199#issueco...
If isInteger was marked as a type guard, then you could write code like this:
function f(s: string | number) {
if (!Number.isInteger(s)) {
console.log(s.substring(0, 0));
}
}
which is clearly wrong.There's an open feature request for a new kind of "one-sided" type guards that don't cause narrowing when they return false.
const intSymbol = Symbol('integer')
type integer = number & {[intSymbol]: never}
const isInteger = (n: unknown): n is integer => Number.isInteger(n)
function f(s: string | number) {
if (isInteger(s)) {
const allowed = s.toExponential()
} else {
// s still string | number
}
}
With this you even get to define functions that must accept integers, which is kinda neat. if (typeof s === 'number' && Number.isInteger(s)) {What I was showing here is that this solution is simpler than yours and just as good. Rather than add a utility function and a faux primitive type, I just do the normal workaround for TypeScript not supporting this, which is to redundantly check that something is both a number and an integer.
The critical bit is that you need to define a new type for `integer`s distinct from `number`s to allow reusing the code in a way that doesn't break the type system on the negative path, as Ryan and I demonstrated.
If it's in terms of performance, that seems like moving the goalposts. I also wonder if it could be optimized away.
Next time I run into it I might use this:
if (Number.isInteger(s)) {
const allowed = (s as number).toExponential()
...and keep the isInteger check close enough that it's readable....or this:
if (Number.isInteger(s)) {
const n = s as number // should be optimized away by the compiler I thinkWhatever floats your boat, as you say.
Have a nice day.
interface NumberConstructor {
isInteger(n: unknown): n is number & { Symbol(): never }
}Currently: either string OR number
Possible: either string | number OR just number
Are you implying in your other comment (that HN won't let me reply to) that Typescript has an "OR" operator that is distinct from "|"? Can you link to documentation on that?
if isInteger(x) is true, x is definitely a `number`
if isInteger(x) is false, x is unknown/unaltered (it remains `typeof x`)
Current type guards can't express "yes versus maybe", so isInteger cannot be a type guard at all.
I absolutely hated how the experimental ones worked and try to avoid using libraries that use it.
Unless you mean the type annotations itself? The good news there is that there is a Stage 1 proposal to take the Python/Ruby approach of bringing them into the language: https://github.com/tc39/proposal-type-annotations
Were that to happen, that proposal doesn't apply any type checking semantics for the browsers themselves and you would still want a type checker, such as Typescript, to actually check the types that are annotated. (Just as you want to run Mypy or Sorbet, respectively, in the cases of Python/Ruby.)
They have to follow the other current and future ECMAscript proposals and implement them though, so new features to be supported has for quite some time dependent almost entirely on the ECMAscript process. On the pure TypeScript side there was only minor tweaking and small corrections (for example, TS 4.8 brought "Improved Intersection Reduction, Union Compatibility, and Narrowing", clearly not a new feature but improvements to an existing one).
At least we get lots of opportunities for interview questions.