r/typescript • • Apr 23 '25

express-generator-typescript@2.6.3 released! This new version uses express v5 and has 3 fewer dependencies.

Thumbnail
npmjs.com
0 Upvotes

r/typescript • • Apr 24 '25

What if your TS types gave you a backend?

0 Upvotes

If you could define your types in TypeScript and instantly get a backend (Postgres, API, realtime queries)… would you use it?

You’d still write logic when needed, but the goal is to stay in TS and skip boilerplate. Services could leverage the same query syntax you'd use on the frontend.

Thinking of a format like this:

type User = {
  id: string
  name: string
  email: string // @unique
  createdAt: Date // @default now
}

type Account = {
  id: string
  user: User
  name: string
  type: 'checking' | 'savings' | 'credit' // @default "checking"
  balance: number // @default 0
  createdAt: Date // @default now
}

which you could query something like this:

const user = query.User({ id: 'u_123' }, {
  include: [{ accounts: 'Account.user' }]
})

// or

const user = realtime.User({ id: 'u_123' }, {
  include: [{ accounts: 'Account.user' }]
})

and get a result like this:

{
  id: 'u_123',
  name: 'Alice Johnson',
  email: 'alice@example.com',
  createdAt: '2024-12-01T10:15:30Z',
  accounts: [
    {
      id: 'a_456',
      name: 'Everyday Checking',
      type: 'checking',
      balance: 1320.75,
      createdAt: '2024-12-02T08:00:00Z'
    },
    {
      id: 'a_789',
      name: 'Holiday Savings',
      type: 'savings',
      balance: 250.00,
      createdAt: '2025-01-01T12:00:00Z'
    }
  ]
}

r/typescript • • Apr 22 '25

Best video courses to learn typescript when you already know javascript

13 Upvotes

I already know JavaScript and would like to learn Typescript. Without having to watch a video course for hours on JS which I already know, is there a good video course on YouTube or Udemy that just teaches you Typescript for people that already know JavaScript?


r/typescript • • Apr 20 '25

Best TS course for react developers

12 Upvotes

I haven't learned ts and I'm good at react. Please suggest TS courses which are beginner friendly along with React.


r/typescript • • Apr 20 '25

[Help] Typescript 5 property decorator that calls function on property change

1 Upvotes

Hello

Is there a way to achieve such behavior without toJSON method so that:

  • I can write exampleObject.value = 123 that will cause side effect function to run
  • I can write JSON.stringify(exampleObject) and have value in that JSON

I've managed to partially make it work with accessor decorator, but then value was not in output JSON and I would have to add toJSON method and that's annoying.

That's my current semi-working decorator: TS playground

Edit: Solution I ended up going with: TS playground - Thanks u/random-guy157


r/typescript • • Apr 20 '25

TypeScript cheat sheet

Thumbnail
gitlab.com
0 Upvotes

Hello there,

I've created a few cheat sheets and there's one for TypeScript that I would like to share with you guys and ask for your opinion if it's missing anything or if it needs fixing somewhere.


r/typescript • • Apr 19 '25

How to bundle typescript without transpilation?

10 Upvotes

I want to bundle my source code into a single typescript file without transpiling it to javascript.

I am trying out the Hermes AOT compilation to native binaries, but it do not support import/export (or require) syntax right now.

To simply, let's start with no third party libs, with just my own code to handle.

All the build tools (esbuild, tsup, rollup, ...) seem to always transpile to javascript. I've also searched on Github and Stackoverflow but I didn't found anything.

Anyone have an idea of how could I archive that?


r/typescript • • Apr 19 '25

I just published my first npm package: rbac-engine - A flexible RBAC system inspired by AWS IAM

6 Upvotes

Hello everyone! I'm excited to share my very first npm package: rbac-engine!

What is it?

rbac-engine is a flexible and powerful role-based access control (RBAC) system with policy-based permissions for Node.js applications. I designed it to provide a robust way to manage permissions across applications, taking inspiration from AWS IAM's approach to access control.

Key Features

  • Role-Based Access Control: Easily assign roles to users and define permissions at the role level
  • Policy-Based Permissions: Create detailed policies using a simple JSON format
  • Flexible Permissions: Support for wildcard patterns and conditional access
  • DynamoDB Integration: Built-in support for Amazon DynamoDB
  • Extensible Architecture: Can be extended to support other database systems

Why I built it

I found that many existing RBAC solutions were either too complex or too simplistic for my needs. I wanted something that had the flexibility of AWS IAM but was easier to integrate into Node.js applications. So I built this package to bridge that gap.

Example Usage

Here's a quick example of how you'd use it:

// Initialize
import { AccessControl, DynamoDBRepository } from "rbac-engine";
const accessControl = new AccessControl(dynamoClient, DynamoDBRepository);

// Create a policy
const adminPolicyDocument = {
  Version: "2023-11-15",
  Statement: [
    {
      Effect: 'Allow',
      Action: ["*"],
      Resource: ["*"]
    }
  ]
};

// Create and assign roles
await accessControl.createRole({id: "admin-role", name: "Admin"});
await accessControl.createPolicy({id: "admin-policy", document: adminPolicyDocument});
await accessControl.attachPolicyToRole("admin-policy", "admin-role");
await accessControl.assignRoleToUser("user123", "admin-role");

// Check permissions
const canAccess = await accessControl.hasAccess("user123", "delete", "document/123");

Installation

npm install rbac-engine

Links

This is my first npm package, and I'd love to get your feedback! What do you think? Any suggestions for improvements?


r/typescript • • Apr 18 '25

Do I have the wrong idea about how much TS will enforce types?

12 Upvotes

Hey y'all. I'm a bit of a TS noob, and I'm converting an older JS project of mine over to TS, mostly as a learning exercise. However I've encountered a situation where I'm scratching my head about the limitations of TS's type enforcement.

My class has a listeners property that's meant to be overridden in the subclass. TS enforces the basic structure of listeners and correctly complains if I try to define something that isn't a function inside, but it doesn't seem to care about the structure of the function itself unless I'm explicit about the type of listeners in the subclass. Why the heck not? Shouldn't it be inferring the signature of the listeners functions from the base class?

If there's a limitation to how much it "nests" the types, how do I tell what that limitation is? My only hint that I'm defining my listeners wrong is an "any" warning. Am I just supposed to sprinkle type hints everywhere? I'm trying to prevent footguns, and having to be explicit everywhere seems opposed to that.

Also I'm confused about why it still doesn't seem to care about the return type in the last example, even though I'm being explicit there.

TS Playground here

interface Event {
  name: string;
  origin: string;
}

type EventListeners = Record<string, (evt: Event, ...args: unknown[]) => void>;

class PluginBase {
    listeners: EventListeners = {};
}

class SomeValidPlugin extends PluginBase {
    override listeners = {
        "someEvent": (evt) => {            // evt is inferred to be type 'any' instead of Event
            console.log(evt.foo);          // No warning about wrong property!
        }
    }
}

class SomeInvalidPlugin extends PluginBase {
    override listeners = {                 // Correct warning about wrong type
        "someEvent": "A string isn't a function",
    }
}

class SomeIncorrectPlugin extends PluginBase {
    override listeners = {
        "someEvent": () => {               // TS doesn't care about function signature
            return "A string isn't void!";
        }
    }
}

class SomewhatCorrectlyEnforcedPlugin extends PluginBase {
    override listeners: EventListeners = { // Why do I have to be explicit about this?
        "someEvent": (evt) => {
            console.log(evt.foo);          // Correct warning about wrong property
            return "A string isn't void!"; // TS *still* doesn't care about return type for some reason
        }
    }
}

r/typescript • • Apr 18 '25

How does Omit work for union types?

8 Upvotes

I've noticed that when trying to Omit union types, it doesn't behave as expected. When I try to Omit 1 common key union, the resulting type only contains the common keys. Does anyone know why this happens? I found a utility type online of:

DeepOmit<T, K extends string | number | symbol> = T extends any ? Omit<T, K> : never 

And this works just fine for unions types but trying to use this utility type for native types like string, the resulting type does not result in type never. For example, declare const test: DistributiveOmit<string, 'key'>. Could this be because Omit is pretty loose in general with what can be removed, and that JavaScript allows for any keys in objects to be called?


r/typescript • • Apr 17 '25

n-params vs single param

Thumbnail carlos-menezes.com
9 Upvotes

r/typescript • • Apr 18 '25

What is the most convienient way to integrate code generation?

0 Upvotes

Hi! I'm building a library that requires calling a command for typescript code generation, and I'm thinking of improving the developer experience. I want to avoid making people call a separate command while keeping the library predictable. What are my options?

The library consists of a CLI and a SDK, so one way I can think of is to call the tool automatically inside the SDK if NODE_ENV is set to development, it's kinda hacky though :) Appreciate your advice here!


r/typescript • • Apr 16 '25

How in the world do people know how to add types to things like THIS?

26 Upvotes

Hey guys, your favorite confused TypeScript beginner is back!

Somebody please explain to me how the heck is one supposed to be able to create a type like this to satisfy the TS compiler when one has no clue how the (scarcely documented) IMaskMixin even works?! How did the person in the second link come up with their convoluted-looking type AND GET IT RIGHT?! Their proposed solution works, but I have no idea why nor how they had the brains to put it together.

See, this is my major blocker/difficulty with TS. How am I supposed to know enough about the above-mentioned IMaskMixin's internals or some other third-party library to provide correct types for it? In the case of the mixin the documentation is barely existent with regard to how to use it, and the API documentation seems complete but looks really scary and completely opaque to my beginner eyes.

I feel totally lost. Typing third-party stuff feels like a huge poke-in-the-dark chore and a major pain in the ass. I feel like TS requires me to know things about third-party libraries that I'd never care to know as a user of these libraries but I must know if I want to shut up my TS compiler.

Please shed some light.


r/typescript • • Apr 16 '25

Is there a way to generate a type based off a list of values dynamically?

17 Upvotes

I'm working on something where there are literally hundreds of order codes, and new ones added and old ones removed every month. I need a type to encompass all of the order codes to enforce in our code.

Type OrderCode = "VOC" | "MLC" | "ENF" ... etc, etc, etc.

Is there a way to generate the type dynamically since it's not practical to update a giant type every month? How would you approach this?


r/typescript • • Apr 15 '25

How does one type currying functions with generics properly?

6 Upvotes

I'm trying to add strong typescript validation to an existing codebase but getting stuck on one of the functions in the project. The function uses optional currying and the typing seems to get lost. Here is the Typescript Playground link:

TypeScript Playground

This is the closest i have gotten to typing it but seems like mapObj in the last line looses its typing.
it gets inferred as

function mapObj<object>(fn: (value: never, prop: never, obj: object) => never): <U>(obj: U) => U

but i Wish for it to infer as

function mapObj<SyncConflict>(fn: (value: DirtyRaw, prop: keyof SyncConflict, obj: SyncConflict) => DirtyRaw): <SyncConflict>(obj: SyncConflict) => SyncConflict

Is this possible?