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
barkbell
Apr 14, 2006

woof
A type assertion. So you are asserting that doAThing returns an object with two keys, foo and bar, which are strings. Don't use with jsx files.

e: Oh I guess it's for generics

barkbell fucked around with this message at 21:15 on Oct 20, 2020

Adbot
ADBOT LOVES YOU

Skyarb
Sep 20, 2018

MMMPH MMMPPHH MPPPH GLUCK GLUCK OH SORRY I DIDNT SEE YOU THERE I WAS JUST CHOKING DOWN THIS BATTLEFIELD COCK DID YOU KNOW BATTLEFIELD IS THE BEST VIDEO GAME EVER NOW IF YOULL EXCUSE ME ILL GO BACK TO THIS BATTLECOCK

necrotic posted:

I think that's a generic function and you're providing a type it needs at call time.

Forgive me, but what in this context is a generic function. I am a bit confused.

edit: I did try googling this but only get results for arrow expressions which is obviously not what I am looking for.

teen phone cutie
Jun 18, 2012

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

Skyarb posted:

Forgive me, but what in this context is a generic function. I am a bit confused.

edit: I did try googling this but only get results for arrow expressions which is obviously not what I am looking for.

generic interfaces look like this

code:
interface MyInterface<T> {
   something: string;
   someNumber: number;
   someData: T
}
where T is whatever type you pass it. the code you posted was where it’s passing the type.

so yeah the sample code you posted it a function that either takes that object or returns it, but you’d have to look at the source for that.

teen phone cutie fucked around with this message at 22:28 on Oct 20, 2020

Roadie
Jun 30, 2013
A simple example:

JavaScript code:
function tail<T>(value: Array<T>): T | undefined {
  return value[value.length - 1]
}
Give it an array of strings with tail(['first', 'second', 'third']) and T will automatically be inferred to a string. Or if you give it an array value it can't infer from, you can manually set it like tail<number>(arrayOfUnknownThings) and will have a return type of number | undefined.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
Somebody wanted inline table editing in our Confluence instance for work so they added a plugin for it. It drives me nuts though, so I'm trying to write a userscript to disable it on all pages. Currently the only way we can disable it with a built in mechanism is on a per-page basis.

It seems like Jira takes all these plugins and combines them into a batch.js file. It's basically got a setTimeout in there looking for tables so it can apply the inline editing on top of them

I'm trying to come up with an easy way to short circuit this thing in a userscript so it doesn't work anymore but I couldn't think of a simple way to do it. Any suggestions?

Skyarb
Sep 20, 2018

MMMPH MMMPPHH MPPPH GLUCK GLUCK OH SORRY I DIDNT SEE YOU THERE I WAS JUST CHOKING DOWN THIS BATTLEFIELD COCK DID YOU KNOW BATTLEFIELD IS THE BEST VIDEO GAME EVER NOW IF YOULL EXCUSE ME ILL GO BACK TO THIS BATTLECOCK
Cool thanks guys. Kinda weird but good to know, I still often feel lost in typescript.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Skyarb posted:

I am back to writing typescript after a long while of NOT doing that.

what the does it mean when a function has `<>`?

for instance:

code:
const something = doAThing<{ foo: string, bar: string }>();

Look up generics.

kiwid
Sep 30, 2013

Are there any JS packages out there that make capturing a picture from the device camera (webcam) easy?

The Fool
Oct 16, 2003


kiwid posted:

Are there any JS packages out there that make capturing a picture from the device camera (webcam) easy?

I mean, this doesn't seem that hard? https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Taking_still_photos

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


He probably meant node.

huhu
Feb 24, 2006
For whatever reason cloudflare doesn't like this code, so image it is.



I'm building a websocket powered application. I'd like to wrap the raw client with a helper function. Clearly what I'm doing in that last line is wrong. What would be the best way in a React app to hook into incoming messages like this, following the structure I've setup?

huhu fucked around with this message at 04:41 on Oct 27, 2020

Roadie
Jun 30, 2013

huhu posted:

For whatever reason cloudflare doesn't like this code, so image it is.



I'm building a websocket powered application. I'd like to wrap the raw client with a helper function. Clearly what I'm doing in that last line is wrong. What would be the best way in a React app to hook into incoming messages like this, following the structure I've setup?

So where's the definition of my_func?

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Is it just me or is it annoyingly hard/frustrating, atleast as a newbie, to connect a sql database to Javascript? Am I just doing something wrong? I can't even find a straight answer on how to do it

MrMoo
Sep 14, 2000

You’ll have to find a “web scale” SQL server, I’m sure there are some out there.

In NoSQL land it’s trivial for access, especially for things like CouchDB where the index can itself be written in JavaScript.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Yeah I'm trying to tie into postgres, but I'm probably just way in over my head. Just trying to make a simple form that creates data on a database. I set it up with Mongo which seemed stupidly easy but this is just "whaaa"

Roadie
Jun 30, 2013

Empress Brosephine posted:

Is it just me or is it annoyingly hard/frustrating, atleast as a newbie, to connect a sql database to Javascript? Am I just doing something wrong? I can't even find a straight answer on how to do it

node-postgres is dead easy to use for a Node server.

JavaScript code:
const { Pool, Client } = require('pg')

// a  set of env vars will be used to initialize the connection
const pool = new Pool()

const res = await pool.query('SELECT $1::text', ["here's some text"])

// shut down the pool when stopping the server
await pool.end()

Empress Brosephine posted:

Yeah I'm trying to tie into postgres, but I'm probably just way in over my head. Just trying to make a simple form that creates data on a database. I set it up with Mongo which seemed stupidly easy but this is just "whaaa"

It sounds like you're trying to do this entirely from a frontend, but you generally need a server in the middle for basic security and access control reasons.

The closest thing to an exception is row-level security like Postgres has, or similar functionality with services like Firebase, and in that case you need to build out authentication and security management before you do anything else.

Roadie fucked around with this message at 03:22 on Nov 1, 2020

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
I'll check them out bi wasn't too concerned with authentication since it would be used Internally. I should probably just look into MS Access lol

barkbell
Apr 14, 2006

woof
i dont know anything about ms access but setting up a node server is extremely easy with libraries/frameworks like express

The Fool
Oct 16, 2003


Empress Brosephine posted:

I should probably just look into MS Access lol

No, don’t,

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

Roadie posted:

node-postgres is dead easy to use for a Node server.

JavaScript code:
const { Pool, Client } = require('pg')

// a  set of env vars will be used to initialize the connection
const pool = new Pool()

const res = await pool.query('SELECT $1::text', ["here's some text"])

// shut down the pool when stopping the server
await pool.end()



Yeah node postgres is fine. Don't connect directly to database from browser please.

Volguus
Mar 3, 2009

Osmosisch posted:

Yeah node postgres is fine. Don't connect directly to database from browser please.

Or this

Ytlaya
Nov 13, 2005

edit: Hm, I think I found what the issue is for the second and third (IE JS not supporting the ellipsis spread syntax or default parameter values), and I'm guessing the issue with the first is something similar. Is there any reason why IE is like this? Safari also seems to frequently have problems that Firefox/Chrome don't have. Might be okay to ignore this since presumably people are using Edge now instead of IE usually, hm.

I'm getting syntax errors from a couple lines in IE that don't give errors in either Firefox or Chrome. The lines in question:

code:
attr_keys = Object.keys(js_data.attributes).sort((a, b) => (js_data.attributes[a].name > js_data.attributes[b].name) ? 1 : -1)
code:
val_range = Math.max(...y_values['samples_all']) - Math.min(...y_values['samples_all'])
Does anyone know what the issue might be? There's no information about the errors other than "syntax error."

edit: There's also a third one where a function is defined that gives the error "expected ')'" which seems strange given there's definitely a closing parenthesis there (and there's no similar error in firefox or chrome):
code:
get_bar_range = function(sample_vals, sample_errors = null){

Ytlaya fucked around with this message at 21:18 on Nov 12, 2020

Obfuscation
Jan 1, 2008
Good luck to you, I know you believe in hell

Ytlaya posted:

edit: Hm, I think I found what the issue is for the second and third (IE JS not supporting the ellipsis rest syntax or default parameter values), and I'm guessing the issue with the first is something similar. Is there any reason why IE is like this? Safari also seems to frequently have problems that Firefox/Chrome don't have.

Yeah IE doesn't support arrow functions or the spread operator since those are from ES6 and IE hasn't been updated in forever. Look into Babel for transpiling your code to an older standard.

Impotence
Nov 8, 2010
Lipstick Apathy
Probably works in Edge though

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
What's a decent and common UI toolkit package for Electron? For creating desktop apps, or something that looks like it. I'd like to tinker around and evaluate it.

Impotence
Nov 8, 2010
Lipstick Apathy
I use vue + element-ui a lot

Boz0r
Sep 7, 2006
The Rocketship in action.
I'm a JS noob and we're using window.fetch to call a web api to retrieve some data. Some of this rarely changes, so I'm trying to implement a cache, and trying to figure out how to do expiration, but it occurred to me that this functionality might be built-in in the browser. Am I wasting my time? I can't seem to find a time stamp on the requests, so I'm not sure if I'm missing something, or if I have to do this myself.

code:
    class CachedFetch {

        private readonly cache: Cache;
        private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };

        constructor(cache: Cache, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
            this.cache = cache;
            this.http = http ? http : <any>window;
        }

        public fetch(url: RequestInfo, init?: RequestInit): Promise<Response> {
            let cache: Cache = this.cache;

            return cache.match(url)
                .then((response) => {
                    if (response == undefined) {
                        this.http.fetch(url, init)
                            .then(function (response) {
                                if (!response.ok) {
                                    throw new TypeError('bad response status');
                                }
                                return cache.put(url, response);
                            });
                    } else {
                        return response;
                    }
                });
        }
    }

MrMoo
Sep 14, 2000

A lot of webapis are written by totally incompetent developers such that they do not process etags or If-Modified-Since headers, so it can quite frequently be a good idea. However note in modern practice you should write the app to not care and control the caching more in a service worker. If you can try and use the semantics of offline-first, i.e. serving from cache then running a refresh request in the background. Note Cache is a thing already in browser world.

MrMoo
Sep 14, 2000

I'll just dump this here because :lol:

https://www.youtube.com/watch?v=mUFFbObqNFY

n3m6
Nov 28, 2020
Currently moving a hodge podge of unstructured js code to typescript, and pulling my hair out

gbut
Mar 28, 2008

😤I put the UN🇺🇳 in 🎊FUN🎉


How many load-bearing bugs did you unearth so far?

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.

n3m6 posted:

Currently moving a hodge podge of unstructured js code to typescript, and pulling my hair out

any.

Jazerus
May 24, 2011



that's for the times that you want to pretend you converted something to typescript, not for when you really are converting

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Jazerus posted:

that's for the times that you want to pretend you converted something to typescript, not for when you really are converting

It's sometimes for getting it to stop yelling at you so that you can then actually begin converting. But usually it's just a // TODO: properly type this that stays there forever.

The Fool
Oct 16, 2003


I’ll use any when prototyping something, then I spend twice as long fixing type issues as I did writing the function in the first place

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.

Jazerus posted:

that's for the times that you want to pretend you converted something to typescript, not for when you really are converting

i've gone through the exercise of taking vanilla js and doing stuff like adding google closure annotations or turning it into typescript several times.

once you hit, say, 50~100k loc, it probably will take you longer to annotate the library than it did to write it in the first place, and you're better off rewriting it clean room, unless the original developer wrote really clean, easy to understand code that was mostly static methods and didn't use custom types as parameters (spoiler alert, they didn't).

teen phone cutie
Jun 18, 2012

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


a cool thing about converting JS to TS is getting your coworkers to review the code so you can merge it

I post these PRs in slack on a weekly basis. also have brought up that we have a serious problem with lack PR review on this team in retro multiple times

I refuse to merge without ppl looking at the code b/c people need to learn this poo poo.

Skyarb
Sep 20, 2018

MMMPH MMMPPHH MPPPH GLUCK GLUCK OH SORRY I DIDNT SEE YOU THERE I WAS JUST CHOKING DOWN THIS BATTLEFIELD COCK DID YOU KNOW BATTLEFIELD IS THE BEST VIDEO GAME EVER NOW IF YOULL EXCUSE ME ILL GO BACK TO THIS BATTLECOCK
Still a typescript newb. I am working with typescript and antd for front end design work.

Can someone tell me why when trying to align my columns in a table this doesn't work:

code:
align: 'center',
but this does:

code:
align: 'center' as 'center',
I honestly don't know why the first one throws a type error, wtf is happening here :psyduck:

susan b buffering
Nov 14, 2016

Skyarb posted:

Still a typescript newb. I am working with typescript and antd for front end design work.

Can someone tell me why when trying to align my columns in a table this doesn't work:

code:
align: 'center',
but this does:

code:
align: 'center' as 'center',
I honestly don't know why the first one throws a type error, wtf is happening here :psyduck:

The compiler doesn’t infer string literal types from strings, so in the first snippet it sees just “a string” where a literal type is expected. With the assertion in the second snippet, you are telling the compiler that it is the expected type, and so it passes.

Instead of the specific type name in these situations, you can use ‘as const’ for the same effect.

Adbot
ADBOT LOVES YOU

Skyarb
Sep 20, 2018

MMMPH MMMPPHH MPPPH GLUCK GLUCK OH SORRY I DIDNT SEE YOU THERE I WAS JUST CHOKING DOWN THIS BATTLEFIELD COCK DID YOU KNOW BATTLEFIELD IS THE BEST VIDEO GAME EVER NOW IF YOULL EXCUSE ME ILL GO BACK TO THIS BATTLECOCK

skull mask mcgee posted:

The compiler doesn’t infer string literal types from strings, so in the first snippet it sees just “a string” where a literal type is expected. With the assertion in the second snippet, you are telling the compiler that it is the expected type, and so it passes.

Instead of the specific type name in these situations, you can use ‘as const’ for the same effect.

I am still confused, I am sorry. What are string literal types? I thought a type could only be a string?

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