/r/javascript

Photograph via //r/javascript

Chat about javascript and javascript related projects. Yes, typescript counts. Please keep self promotion to a minimum/reasonable level.

All about the JavaScript programming language.

Subreddit Guidelines


Specifications:


Resources:


Related Subreddits:

r/LearnJavascript

r/node

r/typescript

r/reactjs

r/webdev

r/WebdevTutorials

r/frontend

r/webgl

r/threejs

r/jquery

r/remotejs

r/forhire


/r/javascript

2,395,704 Subscribers

0

[AskJS] For TypeScript power users: How do you handle Node.js and Bun types in the same script?

Here's one relevant part of a piece of JavaScript runtime agnotic code that tsc Version 5.8.0-dev.20241109 throws errors for.

The code works as expected as JavaScript, without any errors being thrown, becuase there are no errors in the JavaScript code.

  • @types/node/module.d.ts has its own internal errors at dirname and filename which I'm not really concerned about
  • TypeScript's internal lib.dom.d.ts and @types/node and Bun's @types/bun all declare fetch

It appears like there's no way for tsc to make a deicsion which type to apply for fetch when the imported types all declare fetch, and no option to instruct tsc to use X type when X, XX, XXX types from libraries all refer to the same named declaration.

Of course the immediate solution is the use --skipLibCheck which makes using TypeScript utterly useless. We just use TypeScript syntax for the hell of it.

How would Microsoft TypeScript power users handle this case of conflicting types?

import process from "node:process";
const runtime: string = navigator.userAgent;
const buffer: ArrayBuffer = new ArrayBuffer(0, { maxByteLength: 1024 ** 2 });
const view: DataView = new DataView(buffer);
const encoder: TextEncoder = new TextEncoder();

let readable: NodeJS.ReadStream & { fd: 0 } | ReadableStream<Uint8Array>,
  writable: WritableStream<Uint8Array>,
  exit: () => void = () => {};

if (runtime.startsWith("Deno")) {
  ({ readable } = Deno.stdin);
  ({ writable } = Deno.stdout);
  ({ exit } = Deno);
}

if (runtime.startsWith("Node")) {
  readable = process.stdin;
  writable = new WritableStream({
    write(value) {
      process.stdout.write(value);
    },
  }, new CountQueuingStrategy({ highWaterMark: Infinity }));
  ({ exit } = process);
}

if (runtime.startsWith("Bun")) {
  readable = Bun.file("/dev/stdin").stream();
  writable = new WritableStream<Uint8Array>({
    async write(value) {
      await Bun.write(Bun.stdout, value);
    },
  }, new CountQueuingStrategy({ highWaterMark: Infinity }));
  ({ exit } = process);
}

Run tsc and see what happens

node_modules/.bin/tsc --esModuleInterop index.ts
node_modules/@types/node/globals.d.ts:509:14 - error TS2300: Duplicate identifier 'fetch'.

509     function fetch(
                 ~~~~~

  node_modules/bun-types/globals.d.ts:1029:6
    1029  var fetch: Fetch;
              ~~~~~
    'fetch' was also declared here.

node_modules/@types/node/module.d.ts:360:13 - error TS2687: All declarations of 'dirname' must have identical modifiers.

360             dirname: string;
                ~~~~~~~

node_modules/@types/node/module.d.ts:366:13 - error TS2687: All declarations of 'filename' must have identical modifiers.

366             filename: string;
                ~~~~~~~~

node_modules/bun-types/bun.d.ts:117:8 - error TS2420: Class 'ShellError' incorrectly implements interface 'ShellOutput'.
  Property 'bytes' is missing in type 'ShellError' but required in type 'ShellOutput'.

117  class ShellError extends Error implements ShellOutput {
           ~~~~~~~~~~

  node_modules/bun-types/bun.d.ts:434:3
    434   bytes(): Uint8Array;
          ~~~~~~~~~~~~~~~~~~~~
    'bytes' is declared here.

node_modules/bun-types/globals.d.ts:1029:6 - error TS2300: Duplicate identifier 'fetch'.

1029  var fetch: Fetch;
          ~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28708:18
    28708 declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
                           ~~~~~
    'fetch' was also declared here.
  node_modules/@types/node/globals.d.ts:509:14
    509     function fetch(
                     ~~~~~
    and here.

node_modules/bun-types/globals.d.ts:1939:12 - error TS2687: All declarations of 'dirname' must have identical modifiers.

1939   readonly dirname: string;
                ~~~~~~~

node_modules/bun-types/globals.d.ts:1942:12 - error TS2687: All declarations of 'filename' must have identical modifiers.

1942   readonly filename: string;
                ~~~~~~~~

node_modules/bun-types/overrides.d.ts:3:29 - error TS2305: Module '"bun"' has no exported member 'PathLike'.

3 import type { BunFile, Env, PathLike } from "bun";
                              ~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:16004:11 - error TS2430: Interface 'MessageEvent<T>' incorrectly extends interface 'Bun.MessageEvent<T>'.
  Types of property 'ports' are incompatible.
    Type 'readonly MessagePort[]' is not assignable to type 'readonly import("worker_threads").MessagePort[]'.
      Type 'MessagePort' is missing the following properties from type 'MessagePort': ref, unref, addListener, emit, and 13 more.

16004 interface MessageEvent<T = any> extends Event {
                ~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:26068:11 - error TS2430: Interface 'WebSocket' incorrectly extends interface 'import("/home/xubuntu/bin/node_modules/@types/ws/index").WebSocket'.
  Types of property 'binaryType' are incompatible.
    Type 'BinaryType' is not assignable to type '"arraybuffer" | "nodebuffer" | "fragments"'.
      Type '"blob"' is not assignable to type '"arraybuffer" | "nodebuffer" | "fragments"'.

26068 interface WebSocket extends EventTarget {
                ~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:28708:18 - error TS2300: Duplicate identifier 'fetch'.

28708 declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
                       ~~~~~

  node_modules/bun-types/globals.d.ts:1029:6
    1029  var fetch: Fetch;
              ~~~~~
    'fetch' was also declared here.


Found 11 errors in 6 files.

Errors  Files
     1  node_modules/@types/node/globals.d.ts:509
     2  node_modules/@types/node/module.d.ts:360
     1  node_modules/bun-types/bun.d.ts:117
     3  node_modules/bun-types/globals.d.ts:1029
     1  node_modules/bun-types/overrides.d.ts:3
     3  node_modules/typescript/lib/lib.dom.d.ts:16004
8 Comments
2024/11/09
15:36 UTC

1

Showoff Saturday (November 09, 2024)

Did you find or create something cool this week in javascript?

Show us here!

1 Comment
2024/11/09
08:00 UTC

9

[AskJS] State of OfficeJS?

How mature/solid is the OfficeJS API? I am looking to develop an ExcelAddIn that has accessed to users' filesystem. I come from the VSTO world in C# and was looking for opinions of anyone currently developing in it.

Thanks!

11 Comments
2024/11/08
19:16 UTC

4

[AskJS] i know it is 2024, but i still have questions about js and ts

when i work in company, my leader told me that ts has a lot of problems, if you want to develop a Project by ts, you should be more careful. So in my company, most of projects are developed by js. I don't know if this is because the company is not big enough. but the fact is when i learned ts many years ago, i almost never use it in a enterprise level project, i just use it in my own little project. Can anyone help me answer this question? Should I use ts more instead of js in development? THANK YOU VERY MUCH!!!(Modified, sorry that the description of the problem was not clear before)

64 Comments
2024/11/08
12:37 UTC

2

[AskJS] What's Your Favourite yet Underrated Open Source Library?

I'm trying to check some new Open Source Libraries for my upcoming blog, I would love to hear from you!

10 Comments
2024/11/07
11:35 UTC

0

[AskJS] How would you refactor a builder design pattern?

I have been tasked with refactoring our builder in one of our projects due to poor readability and maintainability. The main reason for this fix was because in a previous task it required a lot of files to be changed for a fairly small task. It has made us question our future maintainability for this project.

How would you go about refactoring a builder?

Example:

export class PayloadBuilderImpl<T extends EnvironmentType> implements PayloadBuilder { private _challenge NonNil<string> = “”;

private constructor(main: Main<T>) { this.main = objects.requireNonNil( main, “required for TxnBuilder.” );

async buildTx(): Promise<Transaction> { // logic to build transaction } }

// Payload Builder Interface export interface PayloadBuilder { buildMsg(): Promise<Message>; }

This is an oversimplified version of what it actually looks like, but this is the just of it.

8 Comments
2024/11/06
17:46 UTC

5

WTF Wednesday (November 06, 2024)

Post a link to a GitHub repo or another code chunk that you would like to have reviewed, and brace yourself for the comments!

Whether you're a junior wanting your code sharpened or a senior interested in giving some feedback and have some time to spare to review someone's code, here's where it's happening.

Named after this comic

1 Comment
2024/11/06
08:00 UTC

1

Your /r/javascript recap for the week of October 28 - November 03, 2024

Monday, October 28 - Sunday, November 03, 2024

###Top Posts

scorecommentstitle & link
6218 commentsSpooky tales to scare your JavaScript developers
4828 commentsMicro Survivors: survivors-like game in less than 14kB of JS
186 commentsWasmer JS SDK has just landed full support for Node.js and Bun
176 commentsHalloween.dev - Terror-themed programming challenges [JavaScript & TypeScript]
1627 comments[AskJS] [AskJS] Best JavaScript framework for a mostly static, animated product display website?
1011 commentsEasily Make Games that fit on QR Codes! (They're Multiplatform and No App or Internet is Required)
84 commentsA game focussed RNG - seedable, serializable, performant, highly flexible (chancy!), dice rolling, random weighted choices, many distribution profiles, and more... details in comments!
85 commentsJavaScript Truthy and Falsy: A Deep Dive
71 commentsA brief interview with Moonbit creator Hongbo Zhang
61 commentsCheck if a user input string is mixed-script with unicode-script.js

 

###Most Commented Posts

scorecommentstitle & link
055 comments[AskJS] [AskJS] Are you looking forward to Angular 19?
037 comments[AskJS] [AskJS] Which JS is best for backend development and why?
232 comments[AskJS] [AskJS] is java script just for web or can you make games with it?
028 comments[AskJS] [AskJS] Should I leave Javascript behind?
121 comments[AskJS] [AskJS] Why Eslint 9 is not common?

 

###Top Ask JS

scorecommentstitle & link
21 comments[AskJS] [AskJS] GeoMapping/Map js library
016 comments[AskJS] [AskJS] What’s Your Biggest Problem in [Your Field]? I’m Here to Solve It!
08 comments[AskJS] [AskJS] just asking

 

###Top Showoffs

scorecomment
1/u/jeswin said I made this extension for Claude and ChatGPT to converse with your local source code and make edits. Made possible with the new File System APIs in Chrome. It's written in TypeScript. Source code and...
1/u/Exotic_Drawing_9257 said Full Stack web framework with React + Faster. Automatic routes, reload and component bundle. It uses its own RSC engine, combining SSR and CSR. 100% Deno, no Node dependencies. Fully compatible with D...
1/u/Green_Substance5732 said I’d love to share with you all a passion project I finished today: www.codegroupie.com! I find the many developers struggle to find projects to contribute to do CodeGroupie is a platform where you ca...

 

###Top Comments

scorecomment
71/u/makerkit said Because it's a breaking change and many Eslint plugins still do not support it.
37/u/brodega said "We're migrating to a new JS framework!"
34/u/dlm2137 said I took one look at the change log and noped the fuck out
28/u/XPlutonium said we still don’t know if P=NP and therefore don’t know if one way functions for cryptography can exist. a proof or counter for it would be nice
19/u/svish said If you mean passwordless as in "have to check my email for a stupid link every time I login", then I personally hate it. It forces me to leave my browser, find and most likely wait for that stupid ema...

 

1 Comment
2024/11/04
10:06 UTC

6

[AskJS] GeoMapping/Map js library

Hello everyone, I want to isolate or selectively render the map of New York, is there a good library I can use to make it and play around with it? like adding a information panel on click or something, I am currently looking at Leaflet.js but that's where I'm at rn, staring at it.

11 Comments
2024/11/04
05:06 UTC

7

[AskJS] Framework best fit for games like NYT Games?

Hello! I am a beginner dev with little web experience, and a fair amount of Python knowledge. I make crosswords for fun, and I am interested in making my own crossword engine, as I am disappointed by many of the ones I've found online.

I also want to make some clones of certain NYT Games as practice, in the hopes that I am able to make my own one day.

Is there a framework that works well for these kinds of games? All of the ones I can find are either UI frameworks or Game frameworks, and this lands itself somewhere in-between these two. Should I just be using vanilla JS?

7 Comments
2024/11/03
23:26 UTC

4

[AskJS] is java script just for web or can you make games with it?

I was wondering if I could make game in js so I can switch, I was planning to learn js rn but I'm not going to learn it yet until I find out if I could make games with it

43 Comments
2024/11/03
20:40 UTC

0

[AskJS] What’s Your Biggest Problem in [Your Field]? I’m Here to Solve It!

Hey everyone! I'm planning to start a new venture, but I'm still brainstorming ideas. Could you each share a problem or challenge in your specific field that you wish someone would solve? I'm ready to tackle it!

20 Comments
2024/11/03
07:32 UTC

0

[AskJS] Should I leave Javascript behind?

Context (can be ignored)
I am a full stack software engineer with 3 years of experience. I work in a team with a regular engineer and a principal engineer.|

My team is responsible for around 15 micro services in node, 5 apis in Scala, around 20 routes in react and php. We also manage a couple Elasticsearch databases, mongoDB, Postgres and Mysql.

In an average day: I query aws+postgres+mysql, write a pr in node and react. (I have on average 70 PRs per month and am quite comfortable with our stack)

Here are my issues:

  • Every time I run anything in javascript I see at least 5 critical security vulnerabilities (node + react)
  • It's impossible to not have them since there are so many dependencies which makes it impossible to really maintain in a micro service architecture
  • So many packages don't have support after a while. It's impossible to keep up
  • React is honestly so annoying to work with. Every 1-2 years something new is trendy and recommended. Initially PHP was using server side routing, then React introduced client side routing which everyone loved and now I am being told that I should use server side routing because it is better for seo. Because of that our react app which we work on with different teams includes: client side routing AND server side routing. State is also handled differently across the react app which makes it hardcore to know wtf I am supposed to do.

Should I just give up and learn Ruby on Rails?

29 Comments
2024/11/02
21:58 UTC

Back To Top