Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
necrotic
Aug 2, 2005
I owe my brother big time for this!

Combat Pretzel posted:

So in TypeScript, generics are a compile-time thing. Since that's so, why can't I instance generic types? Kinda this sort of stuff.

TypeScript code:
class Foo<T extends SomeBaseClass>{
    someFunc()
    {
        const bar = new T();
        ...
    }
}
If it's about enforcing some constructor notation, you'd figure that could be arranged by some special notation around <T>, but no bueno.

Because the type system is erased at compile time, what would T refer to? There’s no analog here in actual JavaScript so it can’t do anything concrete with T, only referenced as part of the type system.

edit:

Nolgthorn posted:

Confused about what it is. If you want your class to extend another class you should define another class and extend it. Then typescript would surely figure out what you were doing.

He wants to go like this:

code:
const someFoo = new Foo<Bar>();

someFoo.someFunc(); // this will now have a `new Bar();` in place of `new T();`.

Adbot
ADBOT LOVES YOU

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE

Combat Pretzel posted:

So in TypeScript, generics are a compile-time thing. Since that's so, why can't I instance generic types? Kinda this sort of stuff.

TypeScript code:
class Foo<T extends SomeBaseClass>{
    someFunc()
    {
        const bar = new T();
        ...
    }
}
If it's about enforcing some constructor notation, you'd figure that could be arranged by some special notation around <T>, but no bueno.

You can create a factory function for <T extends SomeBaseClass> if you want: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics

You'd still have to get an actual reference for the class you want to instantiate from somewhere though, you can't go off of the type parameter alone. Building off of the example in the link, you could do this for example:

TypeScript code:
class Cage<T extends Animal> {
  animal: T

  constructor(animalClass: new () => T) {
    this.animal = new animalClass()
  }
}

const lionCage = new Cage(Lion);
e: also note the type system distinction here between an instance of T and a constructor function that returns an instance of T.

TheFluff fucked around with this message at 21:15 on Sep 7, 2022

necrotic
Aug 2, 2005
I owe my brother big time for this!
Ah thanks fluff. I was pretty sure there was a way but didn’t have the time at the moment to look!

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
I've seen factory function stuff before. I figure it's remnants coming from C# that hinder me from understanding why I can't just put the drat type in the pointy brackets and have the Typescript compiler do its thing in the background.

TypeScript code:
const lionCage = new Cage<Lion>();
...looks cleaner to me, because it separates the type fed as generics argument from the actual potential constructor parameters. Just some syntactical sugar.

Alas, it's not meant to be I guess.

Combat Pretzel fucked around with this message at 20:43 on Sep 8, 2022

Roadie
Jun 30, 2013

Combat Pretzel posted:

I've seen factory function stuff before. I figure it's remnants coming from C# that hinder me from understanding why I can't just put the drat type in the pointy brackets and have the Typescript compiler do its thing in the background.

TypeScript code:
const lionCage = new Cage<Lion>();
...looks cleaner to me, because it separates the type fed as generics argument from the actual potential constructor parameters. Just some syntactical sugar.

Alas, it's not meant to be I guess.

You can't do that because the type in the pointy brackets doesn't exist. Here's what your code actually looks like once TypeScript is done with it:

JavaScript code:
const lionCage = new Cage();

necrotic
Aug 2, 2005
I owe my brother big time for this!
Yup. TypeScript is not C#, and it becomes JavaScript which is definitely not C#.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Nolgthorn posted:

I found the solution it is the following:

TypeScript code:
// calculate dot product
function calcDotProduct(origin: TPosition, dist: TPosition): number {
    return dist.x * origin.y - dist.y * origin.x;
}
This is apparently called an "outer product" or something like that. It works and has solved my issue, thanks everyone for getting me that far.

In the end I stripped all of this out. Everything really. Instead, I record where the drag handle opposite to the click position is. Then while dragging, depending on which handle it is I record the difference in start position to be position as either plus or minus height or width.

Then, I change the dimensions of the container adjusting it to its aspect ratio based on whether it's too tall or too wide, no need for dot product or outer product. Then, I reposition it so that the opposite drag handle remains in place.

It's that easy.

sausage king of Chicago
Jun 13, 2001
I don't use javascript/typescript too often and I'm running into a issue. I have some .ts files that are just basic models. they look something like:

code:
export interface lordOfTheRings<T> extends BookObject {
  genre: BookGenre;
  title: string;
  author: string;
}
so I build these with npx tsc and the .js files that it's creating look like this:

code:
export {};
//# sourceMappingURL=lordOfTheRings.js.map
which...doesn't look right. I'm guessing something is messed up in my tsconfig.json file, but not sure what that would be. The tsconfig.json looks like:

code:
{
 "compilerOptions":{
	"module": "esnext",
	"target": "esnext",
	"moduleResolution": "node",
	"lib": ["ES2019", "ESNEXT.AsyncIterable"],
	"outDir": "dest",
	"rootDir": "lib",
	"sourceMap": true,
	"experimentalDecorators": true,
	"emitDecoratorMetadata": true,
	"allowSyntheticDefaultImports": true,
	"skipLibCheck": true,
	"strictNullChecks": true
	},
	"include": ["lib"],
	"exclude": ["node_modules"],
	"declaration": true
 }
}
anything stick out here as to why the .js files would be generated that way? or any other idea as to why this would be happening?

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
JS does't support types, so when you compile your TS to JS, it all gets removed. TS is just a tool to help the developer but none of it is actually being run in the browser

Armauk
Jun 23, 2021


Does anyone have experience using Zod (https://github.com/colinhacks/zod) in TypeScript projects?

sausage king of Chicago
Jun 13, 2001

teen phone cutie posted:

JS does't support types, so when you compile your TS to JS, it all gets removed. TS is just a tool to help the developer but none of it is actually being run in the browser

So there is no way to compile the .ts I have into usable .js files?

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

sausage king of Chicago posted:

So there is no way to compile the .ts I have into usable .js files?

i mean, yeah, your TS should compile to JS and be executable after it's converted - I'm just saying if you have a file that has just a bunch of exported types, it's all gonna get scrubbed at compile time and you'll have a "blank" file.

TheFluff
Dec 13, 2006

FRIENDS, LISTEN TO ME
I AM A SEAGULL
OF WEALTH AND TASTE
To clarify that further, an interface is a type, not a value. It says something about the shape of a value but isn't a value in itself. Nothing like that exists in Javascript, it's only useful to the Typescript compiler. For example:

TypeScript code:
let foo: string = "butts"; // compiles to: let foo = "butts";

// interface doesn't compile to anything
interface barShaped {
  farts: string;
}
let bar: barShaped = { farts: "smelly" }; // compiles to: let bar = { farts: "smelly" };
What are you trying to do, though, and what did you expect the JS to look like?

TheFluff fucked around with this message at 20:06 on Sep 19, 2022

jiffypop45
Dec 30, 2011

No Starch keeps kicking out the Javascript crash course book and I realize js changes quick and a lot so thats expected but I do enjoy books/similarly well structured mediums.

What is a good js book for someone that has a good backend understanding but hasn't been able to get into front end (I tried to do django but got lost).

I tried eloquent Javascript but the author felt like he was missing the forest for the trees and treating js like python/java/etc in lieu of a means for making websites.

jiffypop45 fucked around with this message at 21:04 on Sep 19, 2022

sausage king of Chicago
Jun 13, 2001

TheFluff posted:

To clarify that further, an interface is a type, not a value. It says something about the shape of a value but isn't a value in itself. Nothing like that exists in Javascript, it's only useful to the Typescript compiler. For example:

TypeScript code:
let foo: string = "butts"; // compiles to: let foo = "butts";

// interface doesn't compile to anything
interface barShaped {
  farts: string;
}
let bar: barShaped = { farts: "smelly" }; // compiles to: let bar = { farts: "smelly" };
What are you trying to do, though, and what did you expect the JS to look like?

I'm trying to get that to compile into a package so it can be imported and used in other projects. I expected the files generated would have the properties listed, but it has nothing. I didn't know if there was something wrong with my .tsconfig, but I guess I just can't do what I was trying to do...?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

sausage king of Chicago posted:

I'm trying to get that to compile into a package so it can be imported and used in other projects. I expected the files generated would have the properties listed, but it has nothing. I didn't know if there was something wrong with my .tsconfig, but I guess I just can't do what I was trying to do...?

If you want a type to show up in a type definition file so it can used by other libraries, it needs to be declared an export type.

ModeSix
Mar 14, 2009

I am hitting a roadblock on a seemingly simple thing to do, but apparently it's not so simple.

I have a json list and I am trying to find the value (amount) of the item immediately less than or equal to a given value and also the next highest value.

code:
{
  "items": [
    {
      "id": 1,
      "amount": 6,
      "desc": "Item 1"
    },
    {
      "id": 2,
      "amount": 12,
      "desc": "Item 2"
    },
    {
      "id": 3,
      "amount": 24,
      "desc": "Item 3"
    },
    {
      "id": 4,
      "amount": 36,
      "desc": "Item 4"
    }
  ]
}
For example if my value is 20, I would expect to get Item 2 as the one immediately lower and Item 3 as the one immediately higher. I've googled for the last hour and I can't get something that works at all.

I am sure this is much easier than I think but I can't see the forest for all the trees.

Any help is greatly appreciated.

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
Sort list by value, filter out anything with value < target, pick the top 2 items off the sorted list? Or were you looking for an actual code snippet.

chaosbreather
Dec 9, 2001

Wry and wise,
but also very sexual.

sausage king of Chicago posted:

I'm trying to get that to compile into a package so it can be imported and used in other projects. I expected the files generated would have the properties listed, but it has nothing. I didn't know if there was something wrong with my .tsconfig, but I guess I just can't do what I was trying to do...?

You don’t actually have to do anything to your code make a package, if it has a package.json, it’s a package. Just make sure the entry points are set up how you want it. You only need to compile it so it can be used as JavaScript, not typescript.

ModeSix
Mar 14, 2009

minato posted:

Sort list by value, filter out anything with value < target, pick the top 2 items off the sorted list? Or were you looking for an actual code snippet.

About 2 minutes after I wrote my post I figured this out, it was right in front of my eyes the whole time.

code:
 var higher = data.items.find(item => item.amount > totalDonation);
 var lower = higher.id - 1;
So simple.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

sausage king of Chicago posted:

I'm trying to get that to compile into a package so it can be imported and used in other projects. I expected the files generated would have the properties listed, but it has nothing. I didn't know if there was something wrong with my .tsconfig, but I guess I just can't do what I was trying to do...?

if it's the types you want to expose for importing, it looks like you might be doing that already judging by your tsconfig. are you generating d.ts files? that's the file through which the user would go about importing the types and interfaces

e: to further clarify, you have "declaration: true" in your tsconfig, meaning that the TypeScript compiler is both turning your TS code into JavaScript, but also creating d.ts files which are responsible for mapping the JS to the TS interfaces and types when the user imports your JS in their TS files.

Alternatively, if you have a tool like Babel transpiling code as well, it might be useful having the typescript compiler only emit d.ts files with the "emitDeclarationOnly" flag and have Babel take care of the transpilation.

Could you tell us more about your build process? and also what your package.json look like?

teen phone cutie fucked around with this message at 16:41 on Sep 21, 2022

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


ModeSix posted:

About 2 minutes after I wrote my post I figured this out, it was right in front of my eyes the whole time.

code:
 var higher = data.items.find(item => item.amount > totalDonation);
 var lower = higher.id - 1;
So simple.
yes, if your array is presorted by the amount, which your example is. minato's solution deals with unsorted arrays too.

misread the assignment.

I'd use `Array.reduce()` and return an object or a tuple providing immediate lesser and immediate greater values, as it can do it in one pass. Your suggestion is not robust as it doesn't deal with empty arrays, or arrays with only one value, or arrays that can contain only greater or only lesser amounts...

gbut fucked around with this message at 16:23 on Sep 21, 2022

ModeSix
Mar 14, 2009

Help appreciated from all on this. Your suggestions pushed me in the right direction and I am sorting the array prior to searching then capturing the index of the item immediately higher than the value and moving downwards in the array index after that.

Thanks!

fuf
Sep 12, 2004

haha
I think this is a really easy question but anything to do with asynchronous programming and callbacks etc. still fries my brain to an embarrassing degree.

I want to crawl five pages of a website using the node "crawler" package. The url for page 2 comes from the content of page 1, and so on for pages 3-5, so I need to wait until I have the content of the preceding page before queuing up a crawl of the next page.

Really simplified version of the basic crawler:

JavaScript code:
var c = new Crawler();

function CrawlUrl(url){
   c.queue([{
      uri: url,
      callback: function(error, res, done){   
         var $ = res.$;
         let nextPageUrl = $('.nextPageUrl');
   }}])
}
I tried something like this but it doesn't work (it starts a crawl of page 2 but then never calls "HandleCallback" a second time):

JavaScript code:
var c = new Crawler();

function CrawlUrl(url){
   let count = 0;
   QueueCrawl();

   function QueueCrawl(){
         c.queue([{
            uri: url,
            callback: HandleCallback
         }])
      }

   function HandleCallback(error, res, done){
      var $ = res.$;
      url = $('.nextPageUrl');
      count++;
      if(count < 5){
         QueueCrawl();
      }
   }      
}
What's a good way to approach something like this?

edit: I did it with a promise:

JavaScript code:
var c = new Crawler();

async function CrawlUrl(url){
   let count = 0;
   for(var i=0;i<5;i++){
      await Crawl();
   }

   function Crawl(){
      return new Promise((resolve, reject) => {
            c.queue([{
               uri: url,
               callback: function(error, res, done){
                 var $ = res.$;
                 url = $('.nextPageUrl');
                 resolve();
                 done();
             }
         }])
      }
   }      
}
I also realised that my initial code probably would have worked but I was missing the done() which closes the crawler connection so it wasn't queuing up the next crawl properly.

fuf fucked around with this message at 13:34 on Sep 25, 2022

Peachfart
Jan 21, 2017

Not sure if this is the correct thread, but my work wants me to learn Javascript to work with some automation software, and I have always wanted to learn it. But I haven't done any programming since high school. Is there a recommended online resource for learning Javascript?

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer

Peachfart posted:

Not sure if this is the correct thread, but my work wants me to learn Javascript to work with some automation software, and I have always wanted to learn it. But I haven't done any programming since high school. Is there a recommended online resource for learning Javascript?

Modern Javascript is pretty good.

That said, I would heartily recommend using Typescript from the get-go if at all possible, since its typing lets you avoid a lot of really irritating pitfalls caused by Javascript's loose typing and enables automated refactoring.

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


Osmosisch posted:

Modern Javascript is pretty good.

That said, I would heartily recommend using Typescript from the get-go if at all possible, since its typing lets you avoid a lot of really irritating pitfalls caused by Javascript's loose typing and enables automated refactoring.

Seconding this, TS is superior to JS, and is its superset. Meaning: JS _should_ be valid TS, but not other way around. Of course, there are details that don't really work that way sometimes, but the spirit is there.

Unless your API for automation requires vanilla JS. In that case you might be stuck with a specific JS version, or be forced to use some transpiler to get the output you're feeding to the system be the correct JS version.
In the latter case, it should be (relatively) trivial to set up a pipeline that allows you to use TS or modern JS with your automation system. But setting this pipeline requires prior knowledge of JS to some degree.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Peachfart posted:

Not sure if this is the correct thread, but my work wants me to learn Javascript to work with some automation software, and I have always wanted to learn it. But I haven't done any programming since high school. Is there a recommended online resource for learning Javascript?

learn more about the api and get code samples of using the automation interface before looking at books or asking questions. it's easily possible that by "automation api", your workplace means some horrible windows activex poo poo that many of the other people in the thread are too young to have experienced. most people posting here are going to be coming from a "js in browser" or "nodejs" context, and that will hurt you if the actual environment is "we're somehow still using cscript in 2022."

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Osmosisch posted:

Modern Javascript is pretty good.

That said, I would heartily recommend using Typescript from the get-go if at all possible, since its typing lets you avoid a lot of really irritating pitfalls caused by Javascript's loose typing and enables automated refactoring.

And use Jest instead of Mocha

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
https://www.npmjs.com/package/kequapp

Recently updated my Node app framework and am interested in feedback if you like it. <3

Doktor Avalanche
Dec 30, 2008

fuf posted:

edit: I did it with a promise:

I suggest you take a look at async/await, it's much more readable than callbacks and promises.

worms butthole guy
Jan 29, 2021

by Fluffdaddy
I have a function:

code:
const addToCart = (prod) => {

 // do state stuff in here
}
that works. If I try to add the following switch statement to it:


code:
 const addToBuilder = (prod) => {
        let currentItemPrice = 0;
        let productName = "";


        // API call of product library to get Base Price.

        // need a switch case to look up the ID of the selected product

        switch (productInput.current.value) {
            case "instagram_sponsored_post":
                currentItemPrice = 1500;
                return currentItemPrice;
            case "neocon_showroom_tour":
                currentItemPrice = 8500;
                return currentItemPrice;
            default:
                break;
        }

        console.log('got here: ' + currentItemPrice);
        // dispatch this off to state
            dispatch({
                type: "ADD_TO_BUILDER",
                payload: {
                    product_name: productInput.current.value,
                    price: currentItemPrice,
                    quantity: quantityInput.current.value
                }
            })

    }
it gets stuck in that switch statement and I never get to the console.log portion. What stupid & obvious thing am I missing that making this get stuck in the switch statement?

edit: I figured it out; you just break in javascript switch cases unlike PHP ones where you return then break

worms butthole guy fucked around with this message at 22:14 on Oct 3, 2022

FuzzySlippers
Feb 6, 2009

I'm trying to learn typescript better and this error is confusing me. Code:
code:
export interface IEntityEvent {
    entity?: Entity;
    get postParent(): boolean;
}
error:
code:
Failed to compile.

./src/events/entity-event.ts
SyntaxError: C:\Projects\rl-test\src\events\entity-event.ts: Missing semicolon (5:7)

  3 | export interface IEntityEvent {
  4 |     entity?: Entity;
> 5 |     get postParent(): boolean;
    |        ^
  6 | }
I don't understand how a semicolon is supposed to be there. It's doing this on all my getters. I usually write c# but this looks correct to me.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
If your property on the interface can only be read from, you just specify it as readonly postParent;

An implementation of the interface can fulfil that by using a getter, if that's what it wants to do. But that's an implementation detail, all that the interface specifies is that it has a property called postParent that you are allowed to read from.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!
That is a loving terrible error message given how likely this mistake is though. Well worth a "was the string get? Append 'did you mean readonly'" sort of treatment

fsif
Jul 18, 2003

Osmosisch posted:

Modern Javascript is pretty good.

That said, I would heartily recommend using Typescript from the get-go if at all possible, since its typing lets you avoid a lot of really irritating pitfalls caused by Javascript's loose typing and enables automated refactoring.

Disagree about the Typescript from the get go. I'm not sure the benefits of TS really outweigh its added complexity unless until someone already has a pretty good handle on JavaScript. Plus, if they're learning JS in order to interact with already existing automation software, they're probably not going to be able to put much of that TS knowledge to use anyway.

FuzzySlippers
Feb 6, 2009

Thanks and yeah that error sucks.

I've been playing around with ts pondering the idea of using it as an alternative to lua for making a thoroughly mod friendly game. Despite the goofy error I certainly enjoy writing ts a hell of a lot more than lua.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

fsif posted:

Disagree about the Typescript from the get go. I'm not sure the benefits of TS really outweigh its added complexity unless until someone already has a pretty good handle on JavaScript. Plus, if they're learning JS in order to interact with already existing automation software, they're probably not going to be able to put much of that TS knowledge to use anyway.

After I got used to Typescript I just love it too much. Makes writing code so easy, I know what everything is and it always forces me to deal with every possible eventuality.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Nolgthorn posted:

After I got used to Typescript I just love it too much. Makes writing code so easy, I know what everything is and it always forces me to deal with every possible eventuality.

I probably would've discarded typescript as being dumb bullshit if I didn't write javascript for a few years before learning typescript.

Adbot
ADBOT LOVES YOU

fsif
Jul 18, 2003

That wasn't intended as an anti-TypeScript comment (though I do think it's overprescribed by its evangelists) but more a suggestion for someone new to JavaScript. It's hard enough to learn JS; piling on a bunch of TS tooling and type errors and conventions right at the onset of learning, especially to interact with a non-TypeScript tool, feels unnecessarily arduous.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply