r/typescript • • Apr 13 '24

After using Ruby for 2 years, here's some features I'd like to see in Typescript.

1 Upvotes

Context

I love TypeScript. It's my favorite language. I maintain a medium size project (650 files / 30k lines) written entirely in TypeScript, and there's no other language I'd rather use.

2 years ago, I started a new job using Ruby. While I don't like it nearly as much as TypeScript, it has some amazing features that I wish TypeScript had.

Note: I am NOT saying TypeScript is a bad language! These are just things I miss when I use it.


Desired improvements

1. Returning values from if blocks

const result = if (is_dog) {
  'dog';
} else if (is_cat) {
  'cat';
} else {
  'unknown';
}

That code works in Ruby and Rust, but not in TypeScript.

Alternatives:

  • Ternaries

    • Downside: Only works for small ifs.

  • IIFEs

    • Downside: Have to write (async () => {})() each time

  • Setting let result: string | undefined = undefined first, then assigning it in the if expression

    • Downside: Can't use const.

2. Implicit returns

function getResult() {
  3;
}

const a = getResult();

That code returns 3 in Ruby and Rust, but not TypeScript. It may seem small, but it gets really useful for nested functions and ifs.

Alternatives:

  • Typing return 3; instead.

3. Named arguments

function countOccurrences(arr: number[], value: number) {
  return arr.filter(x => x === value).length;
}

const occurrences = countOccurrences(arr: [3, 3, 2, 3, 5], value: 3);

That code works in Ruby, but not in TypeScript.

Alternatives:

  • Use positional arguments

    • Downside: It's easy to mix up the order, and hard to change the order later on, making it less maintainable.

  • Create an interface for the arguments, and take in an object with that interface

    • Downside: It's harder to define default arguments.

  • Edit: You can also write it like this: function countOccurrences({arr, value = 0}: {arr: number[], value?: number})

    • Tiny downside: You need to write each argument name (e.g. arr) twice.

4. An amazing iterator library

const arr = [3, 1, 2, 3, 4, 5, 5, 5]
const how_many_numbers_occur_twice = arr
  .group_by(x => x).values.count(x => x.length == 2)

That code works in Ruby and Rust, but not in TypeScript.

Alternatives:

  • Use Lodash's functions

    • Downside: You need to order this backwards: _.count(Object.values(_.group_by(... and so on.

  • Use Lodash's custom list object

    • Downside: You're left with a custom list object, not a pojo.

5. Using ? and ! to convey meaning

// ? conveys that it's a predicate
function checkIfDog?(animal: Animal);

// For a function that can return null, ! conveys that it'll throw an error instead of returning null
function loadAnimal(id: string): Animal | null;
function loadAnimal!(id: string): Animal;

// For a function that modifies an iterable, ! coveys that it'll modify it in place
function sort(arr: number[]): number[];
function sort!(arr: number[]): void;

That code works in Ruby, but not in TypeScript.

Alternatives:

  • For predicates: function isDog

  • For null-able functions, copy Prisma: function loadAnimalOrThrow

  • For functions that don't modify an iterable: function sort(arr: readonly number[])


Conclusion

For people that got this far: What do you think? Do you want these features in TypeScript, or is the language better without them?


r/typescript • • Jan 30 '25

Two features Typescript will never include

Thumbnail
danielfullstack.com
1 Upvotes

r/typescript • • Feb 24 '24

JSDoc as an alternative TypeScript syntax

Thumbnail alexharri.com
0 Upvotes

r/typescript • • Apr 08 '23

After 800 hours I finally saw why people like TS

5 Upvotes

This morning I branched my codebase and deleted TypeScript from that branch (took about 5 hours) so I was back at pure Javascript. I then spent the next 6 hours coding in pure Javascript. And the first 5 hours were awesome.

But in the past hour I started getting tired, and went to code something complex, and had to go read some documentation. Took me about 10 minutes to read what I needed and implement the code, but I made a few dumb bugs in the code as I did it. And I thought to myself, that TypeScript probably wouldn't have let me make those bugs.

So I switched back to the TypeScript branch and rewrote it. Took only about 5 minutes this time, but I attribute some of that speed improvement to having just done it. However, sure enough TypeScript would have not allowed me to make the bugs, and it also would have given me enough hinting that I may not have needed to go look up the documentation.

FINALLY, after 3 months of a giant screw around operation, I understood what TypeScript gets you.

I still think it's a mess of a language. And in the future when it tells me the types are wrong when I know the code works, I'm just going to tell it to STFU (`//@ts-ignore`), but at least I finally understand why people like this miserable language.


r/typescript • • Mar 30 '25

Why is "readonly" a thing and where did it come from?

0 Upvotes

The keyword "readonly" in TypeScript is quite confusing for beginners and even those who have used the language and advanced types for some time.

LSP says:

Let ⁠ϕ(x)⁠ be a property provable about objects ⁠x⁠ of type T. Then ⁠ϕ(y)⁠ should be true for objects ⁠y⁠ of type S where S is a subtype of T.

An so in this case ϕ(x) is "readonly". That means when type T is defined as { readonly foo: string }
any subtype S must have "foo" be readonly. But we can do this:

type T = {readonly foo: string }
type S = T & {foo: string }
let s : S = {foo: "a"};
s.foo = "b";

And that's fine as long as you understand that "readonly" just means that T only declares that "foo" can be read. It doesn't say that "foo" is immutable. It it meant that the property was "readonly", they could have just used "const".

ϕ(x) is actually just "foo can be read". It doesn't say anything about if it can also be written to.

But Readonly<Type> is described as:

Constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.

This is not true. They can be reassigned.

One thing I don't like in programming languages is when I have to write more to describe a type that does less (has fewer properties). Java is horrible when it comes to that with "final", "private" and all that.

Many use readonly mostly just to communicate that you don't expect that the property is ever mutated. We rarely actually use Object.freeze or Object.defineProperty ... writable: false because many fear it makes the code slower.

But the language TS is based on already has "writable". Why isn't that the keyword we use?
Then "readonly" could be the default and "writable" would extend the property for writability.

The type modifier "readonly" actually just means: "This type does not declare this property as writable"
But it is often understood as: "This property is not writable".
Those are not the same.

And we have get and set (as in public get foo() { return this._foo;}), so why not use that in types as well?

It's just something that really bothers me when I use TS. Not that other object oriented languages are better. Java is a mess with the List interface that has so many immutable implementations but the interface has all the methods for mutation.

Maybe someone knows where that even comes from. Why did they use "readonly" as a modifier? That's not from C# as far as I know.


r/typescript • • Jul 15 '24

In defense of enums in TypeScript

Thumbnail
bluepnume.medium.com
0 Upvotes

r/typescript • • Jan 08 '23

Civet: The modern way to write TypeScript ("CoffeeScript for TS")

Thumbnail
github.com
1 Upvotes

r/typescript • • Aug 28 '26

xtsc: TypeScript compiler, also lowering to native / WebAssembly / JVM bytecode (experimental)

Thumbnail
github.com
0 Upvotes

This project is still very experimental. A complete rewrite of the TypeScript compiler, but instead of Go, using multiplatform Kotlin. I am still hoping to match or even exceed the performance of Microsoft's rewrite. It is not based on the original sources, but on the orginal test suites, and then rewritten from scratch by Claude in a very tight harness I defined and directed.

Writing compiler in KMP, and lowering via Kotlin IR, unlocks many features - for example any TypeScript (no scriptc restrictions - Any is allowed, etc.) compiled to either native binary, or a library to be used on ~20 platforms supported by the Kotlin multiplatform, including WebAssembly and iOS. Still a long way to go, but I want to share it early. It is not production ready, except for particular use cases where it might work for you really well. I am getting towards usable state and working on better documentation.


r/typescript • • Aug 28 '26

Pure TypeScript Dice Roll

3 Upvotes

It came to my attention that no TypeScript dice-roll libraries exist.

The existing ones are JS in disguise: when you tell it to roll('2d6 + 3'), it returns a `number`.

I wanted a real roll. Roll at compile time.

Because if not compile time, then when? Compile time is the best time.

Anyways. It includes a custom PRNG (pseudo-random number generator) too to support the rolls, which generates random numbers at compile time too. I think there are some for TS out there, unlike dice rolls, but I needed to optimise a bit specifically for 1-100 rolls (who rolls more than that? Only mad people, and we are not the ones).

It has a JS "mirror" implementation. If you rolled 20 in TS, you can be sure you rolled 20 in JS too.

And if a compile-time value is not known, it still works and falls back the result types to `number'.

Basic use case looks like:

// seed
const initialized = initialize([
  "00000001",
  "00000002",
  "00000003",
  "00000004",
] as const);

const d20 = evaluate("d20", prngStateOf(initialized));
const d20Value = valueOf(d20);
//    ^? const d20Value: 12

Enjoy!


r/typescript • • Oct 05 '19

I am concerned about the low quality of NPM packages. What has been your experience?

0 Upvotes

For a syntax tree visualizer I am implementing, I need a way to convert an index referring to a position in a string to a line and column index.

I am looking for a lib (with typescript types) that does only that (optionally allowing to convert a line and column back to a position) and does that sufficiently fast.

So I searched on npm for "position line". And found quite a few packages:

  1. https://www.npmjs.com/package/line-info (94 downloads per week)

  2. https://www.npmjs.com/package/get-line-from-pos (3.7k downloads per week)

  3. https://www.npmjs.com/package/find-line-column (40k)

  4. https://www.npmjs.com/package/src-location (58)

  5. https://www.npmjs.com/package/vfile-location (1.533k)

  6. https://www.npmjs.com/package/translocator (1)

  7. https://www.npmjs.com/package/line-column (14k)

(1)-(4) all provide the functionality by having a function that takes a position and a string and returns something. This already is super inefficient when doing this thousands of times on the same string, as already their APIs don't allow (sane) implementations that support caching where the line breaks are.

(1) is providing a very specific functionality that returns the line string, words and word value but not the line and column number of the cursor (exactly what one would expect from a package called line-info... (irony)).

(2) only returns the line, its implementation fits into 4 very short lines.

(3) is super inefficient and does not support \\r\\n. They split the input two times by \\n. It's just horrible.

(4) is inefficient (not as inefficient as 3 though) due to absence of caching.

(5) caches, but has a very weird dependency to vfile. Only when you look at the code you see that this dependency is not a real one. It's algorithm is also not the best one (linear search on the cache).

(6) I cannot find its source and it's weird that it only operates on ranges, not single positions. You can easily implement the functionality for ranges if you already have it for positions, but the otherway round you are wasting a lot of cpu cycles.

(7) This is actually a decent implementation. Sadly, it does not have typescript type definitions. Typing that library is almost as much work (including a PR for definitely typed) as just writing my own library. Probably this is what all the other six guys thought too.

Conclusion: Of these 7 libraries, 6 are not of high quality. The single decent one has no typescript type definitions. Why are there seven libraries doing almost the same in the first place??

This happens a lot when I search a package on NPM. Most libraries have a bad design, use inefficient algorithms or are untypeable. This is sad.

What have been your experiences when looking for a package on NPM?

I've started the same discussion in the JS subreddit and am curious whether TypeScript developers see this differently.


r/typescript • • Dec 16 '24

TypeScript flashcards

Thumbnail cards.samu.space
1 Upvotes

r/typescript • • Sep 25 '24

New VS Code Extension: Comment Out all console.log Statements with a click!

0 Upvotes

Hey everyone!

I just released a new open-source VS Code extension called //ConsoleLog. If you’ve ever had to go through your code commenting out console.log statements before committing or deploying, this might save you some time!

The extension automatically comments out all console.log statements in any active JavaScript or TypeScript file, including multi-line logs. It’s a small tool to help clean up your code quickly while preserving indentation and formatting.

It’s open-source, so if anyone wants to contribute, feel free to check out the GitHub repo. Feedback and contributions are always welcome!

You can also find it on the VS Code Marketplace: Console Log Commenter

Would love to hear your thoughts!


r/typescript • • Aug 23 '21

Why are types making a comeback?

0 Upvotes

I'm a ruby developer, growing up with then modern languages like Ruby and Phython that kicked out types and went for duck-typing instead. Back then types didn't do much for Java and C# but be a hassle for developers, so things went to specs and behaviour driven design - creating a very solid safety-net through tests.

I have seen the power of strict types in Haskell - and they can be amazing - but only if you're very strict and consistent.

Now we seem to be in a situation where Javascript resists test frameworks - or at least they have less value and provide less of a safety-net than in other languages and we're instead going back to types.


r/typescript • • Sep 06 '21

Explain like I’m 5, why should I (a React dev) use typescript?

1 Upvotes

We’re bringing on some new hires at the company I work at (large scale React web app), all of whom have typescript experience and are already including typescript in their commits.

I’m an experienced Rect developer but I just can’t get my head around why we should use typescript.

Can someone explain it to me like I’m an imbecile?


r/typescript • • Apr 21 '26

Just open-sourced a TypeScript SDK + protocol that lets AI agents call typed actions inside your running app (Zod-first, Standard Schema, MCP-native)

0 Upvotes

Been building a fairly complex UI-heavy app for myself recently, and at some point I tried to hand parts of it over to an agent. Went through the usual options: Playwright scripts, Chrome extensions, Computer Use-style screenshot loops. All of them were slow, brittle, and full of "ok now find the button that opens the dialog that contains the form" failure modes. The agent would miss a click, trigger the wrong dropdown, fight the React re-render, etc.

It finally clicked that the problem wasn't the agent. It was the interface I was forcing the agent to use. I was making it drive a human UI instead of giving it a programmatic surface. So I pulled out the piece I'd been reinventing app-by-app and turned it into a protocol and a set of SDKs. Open-sourced as Tesseron last week, v1.0.0.

What it actually is, in TypeScript terms:

A builder API for declaring typed actions and resources inside your existing code, plus a tiny local gateway that re-exposes them to any MCP-compatible client. The SDK itself is pure TS with Standard Schema support, so you can validate with Zod, Valibot, ArkType, whatever. Handler types are inferred end-to-end from the input schema.

import { tesseron } from '@tesseron/web';
import { z } from 'zod';

tesseron.app({ id: 'invoices', name: 'Invoices' });

tesseron
  .action('createInvoice')
  .description('Create a draft invoice for a customer')
  .input(z.object({
    customerId: z.string(),
    lineItems: z.array(z.object({
      description: z.string(),
      amountCents: z.number().int().positive(),
    })).min(1),
  }))
  .output(z.object({ id: z.string(), total: z.number() }))
  .handler(async ({ customerId, lineItems }, ctx) => {
    const confirmed = await ctx.confirm({
      question: `Create invoice for customer ${customerId}?`,
    });
    if (!confirmed) throw new Error('User cancelled');
    return await api.createInvoice({ customerId, lineItems });
  });

await tesseron.connect();

ctx carries MCP primitives so handlers can pause mid-run:

  • ctx.confirm({ question }): yes/no, surfaced natively in the agent's UI, not as another model turn

  • ctx.elicit({ schema, question }): typed, schema-validated form back from the user

  • ctx.progress({ percent, message }): streaming status while the handler runs

  • ctx.sample({ prompt }): call the agent's LLM inline (generate a commit message from inside a deploy handler, etc.)

.output(schema) is optional but adds typed result inference and runtime validation. Standard Schema support means the validator is pluggable, and the result types flow through to the handler signature.

Packages on npm (all at 1.0.1):

  • @tesseron/core: protocol types + action builder, zero runtime deps beyond Standard Schema

  • @tesseron/web: browser SDK

  • @tesseron/server: Node SDK

  • @tesseron/react: hooks adapter

  • @tesseron/mcp: local gateway server (CLI)

How it works at runtime:

Your app opens a WebSocket to a local gateway (default ws://127.0.0.1:7475). The gateway registers each app's actions as MCP tools and re-exposes them over stdio to whichever MCP client the user has open (Claude Code, Claude Desktop, Cursor, VS Code + Copilot, Codex, Cline, anything else that speaks MCP). Tools appear and disappear as apps connect and disconnect. A six-character claim-code handshake ties one running app to one agent session, so the gateway knows which app is being driven.

No DOM scraping, no MCP-server-per-app, no browser automation. Your real handler runs in your real process against your real state. The mental model I keep coming back to: it's an accessibility layer for AI agents. You instrument the app once, the way you'd add ARIA to a web page, and every MCP client can then drive it.

Examples in the repo (same todo app, six stacks): vanilla TS, React, Svelte, Vue, plain Node, Express.

License:

  • Reference implementation: BUSL-1.1 (free for in-app and self-hosted use, auto-converts to Apache-2.0 four years after each release; the only blocked case is offering Tesseron-as-a-service)

  • Protocol spec: CC BY 4.0, so a Python, Rust, Go, whatever implementation is explicitly encouraged

Python and Rust (for Tauri) are on the roadmap.

Links:

Full disclosure I'm the author. Would particularly love feedback on the builder ergonomics, the Standard Schema integration, and the ctx surface. If anything feels un-TypeScript-y I want to know before it calcifies.


r/typescript • • Jul 08 '21

How an Anti-TypeScript “JavaScript Developer” Like Me Became a TypeScript Fan

Thumbnail
betterprogramming.pub
2 Upvotes

r/typescript • • Mar 14 '24

User-defined type guards are not safe

Thumbnail joshhunt.dev
0 Upvotes

r/typescript • • Jun 07 '25

How I structure Zod schemas, personally

0 Upvotes
export class ProductDTOSchema {
  static Read = z.object({
    id: z.number(),
    title: z.string(),
    content: z.string(),
  });
  static Create = ProductDTOSchema.Read.omit({
    id: true
  });
  static Update = ProductDTOSchema.Create.partial();
}

export type IProductDTO = IndexedClassDTO<typeof ProductDTOSchema>;

// Other file
export type IndexedClassDTO<DTO> = {
  [Schema in Exclude<keyof DTO, "prototype">]: DTO[Schema] extends z.ZodType<
    infer T
  >
    ? T
    : never;
};

Just wanted to share


r/typescript • • Oct 19 '21

TypeScript is the Only Programming Language you Need: TypeScript Everywhere

28 Upvotes

Hi,

Recently, I've worked on different projects where I only TypeScript as the programming language. One of major advantages to use the same language is to reduce context switching.

You only need to use one ecosystem: one package manager, one linter, one code formatter, etc. You only need to configure once and share it across all your projects. Saving you a ton of time ;)

Here is the list you where you can use TypeScript for almost everything:

- Frontend development with React, Next JS supports out of the box TypeScript

- Backend development with Serverless Framework and Express JS

- Infrastructure as Code with AWS CDK

- Mobile development with React Native and Expo framework

- Machine learning with Tensorflow JS

- Smart assistant with Alexa using TypeScript

TypeScript can now be used everywhere and make the development much smoother with only one programming language to learn. No more context switching between programming language and all the stack is unified.

Could we use TypeScript for everything? Is TypeScript the only language you need to learn?

Original post from: https://creativedesignsguru.com/typescript-everywhere/


r/typescript • • Nov 09 '19

Text game in Typescript

0 Upvotes

Hello, I'm currently working on a wrestling bot that simulates a wrestling match between two people on discord. The principles of the bot are written already but I'm stuck as this was a project made by a friend who had to stop because of health issues.

I'm looking for someone that has basic knowledge of TS that could help out finish the project? I also the version of this game written in mIRC Scripting which I did myself but I can't transfer any of that to TS or JS, unfortunately, as my skills are limited to none.

Please reply here or dm me if interested in the project.


r/typescript • • Dec 25 '25

Typescript and module resolution

0 Upvotes

Anyone have some pointers for a TS newbie to make some sense of the pile of hot garbage that is Typescript module resolution? Blown well over an hour tweaking tsconfig.json and tsc still can’t seem to find the npm modules that just plain work in plain old node.js.


r/typescript • • Apr 29 '25

Breaking the Enum Habit: Why TypeScript Developers Need a New Approach - Angular Space

Thumbnail
angularspace.com
1 Upvotes

Using Enums? Might wanna reconsider.

There are 71 open bugs in TypeScript repo regarding enums -

Roberto Heckers wrote one of the best articles to cover this.

About 18 minutes of reading - I think it's one of best articles to date touching on this very topic.


r/typescript • • Mar 12 '25

How do you get started with React + Typescript

0 Upvotes

I have been trying to get used to using Typescript with React and im kind of lost at this point.

What are the key concepts should i master without over complicating everything?


r/typescript • • Sep 13 '25

Yet another starter project. This time showcasing type-safe JavaScript using TS-compatible JSDoc

Thumbnail
github.com
0 Upvotes

Roast me.