« first day (4434 days earlier)      last day (512 days later) » 

1:07 AM
In typescript is there a way to define a key value pair type?
export type DataType = {
   items: number{};
}
var item = new Item();
var index = 0;
dataType.items[index] = item;
basically, i'm trying to define the type of key value pair
// guessing
 
@1.21gigawatts Please don't post unformatted code - use the up arrow to edit your post, then hit Ctrl + K to format the code in that post. See the faq. You have 25 seconds to edit and format your message properly before it will be removed. Please separate code blocks from your actual question. Put your question in 1 message and then your code in a 2nd and format it.
 
export type DataType = {
   items: number<Item>{};
}
 
1:37 AM
@Wietlol it's a challenge to pay for anything from Russia now (what with the invasion and Visa and MasterCard closing up shop in the country). That trial period requires your credit card information
 
ah, you are from russia
that might complicate things a bit yea
not everything requires premium though
if you skip the one that now requires premium, you might find other lessons that do not need it
i guess best option for now is just to skip the PRO stuff
although, perhaps it might be better to find a different course then
perhaps this one would suffice learnjavaonline.org
also, if you write code outside of the browser, use IntelliJ (Community Edition)
it will help you a lot
 
 
3 hours later…
5:13 AM
Kevin.
Hello

Can this for Loop be written as forEach instead?
for (let i = 1; i <= 96; i++) {
players.add(".playSingle" + i);
}
Is that something that is able to be done?
Would someone else on here be able to answer this?
 
 
2 hours later…
7:02 AM
@MarySmithJames .forEach() is when you have an array and want to execute something for each item. You don't have an array here. Unless 96 is supposed to be the length of one but it's not evident. If you just want to create an array of 96 items, you can use Array.from({ length: 96 }, (_, i) => ".playSingle" + (i +1)) However, this is not fully equivalent, as it creates, doesn't add to an already existing array with data.
 
7:14 AM
Why it's not possible to define /[^0-9]/gi, '' as REGEX ?
but I need to hardcode
like this
values.sms_code.replace(/[^0-9]/gi, ''))
 
Because it's two parameters. The first is the regex, the second is the replacement string which here is an empty string.
A variable doesn't hold two values ever. Just one. E.g., var x = 1, 2 does not make sense.
 
7:34 AM
Thank you
 
7:51 AM
:55644289   Array.from({
      length: 96
    }, (_, i) => players.add(".playSingle" + (i + 1))

 });
 
@MarySmithJames Please don't post unformatted code - use the up arrow to edit your post, then hit Ctrl + K to format the code in that post. See the faq. You have 25 seconds to edit and format your message properly before it will be removed. Please separate code blocks from your actual question. Put your question in 1 message and then your code in a 2nd and format it.
 
It's not worth doing that.
You're not using the resulting array.
If you really need "different" you can use a generator:
function* seq(from, to) {
  for (let i = from; i < to; i++)
    yield i;
}

function forEach(iterator, fn) {
  for (const item of iterator)
    fn(item);
}

forEach(seq(1, 96), i => players.add(".playSingle" + i));
But I think it's hardly worth it.
Note that seq is also very simplistic. Doesn't do reverse generation like seq(10, 1) which should probably count 10 to 1. It's just an illustrative example.
The fact that you'd have to re-invent a for loop as a generator is kind of annoying. If you already have a seq helper, then it's trivial to use it. But if you don't and you don't have the forEach helper, either, then it's probably not worth inventing them just for this trivial problem.
 
 
6 hours later…
1:59 PM
when software is in a gitlab repo, and, the specific repo is of type monorepo (and not publicly available on npm) - how do you add specific dependency of the monorepo to your project? For e.g. Say there is a monorepo foo which exposes multiple npm modules...say one of them is called bar. How can I install bar as dependency of my nodejs project, but reference it from my gitlap repo?
 
 
3 hours later…
5:25 PM
is there a way to decast an object?
 
wat
 
!!wat
 
lol
I want to tell the compiler to treat my object as an object instead of as a specific class
0
Q: Is there a way to decast or lowercast an object so that design time typing stops complaining?

1.21 gigawattsI have a request that contains a property that contains the form that also contains a property. See code below. VSCode is giving me an error on the form properties that I have. Here is my code: async respond(request: Request, response: Response, next: any) { var form = request.body; var nam...

As example, let's say I have a Dude class that extends from Person
Shouldn't I be able to go like this:
var dude: Dude = new Person() as Dude
Or:
var person: object = new Person();
 
5:50 PM
1. Please, avoid noise in questions
 
@1.21gigawatts Let's swap slightly for an example: obj = new Animal() as Cat would that be correct? What happens when you call obj.meaw()?
 
2. There is no such thing in TS as casting - we only have type assertions
3. You can assert as unknown as <whatever>, just remember that it is inherently unsafe
 
I might need to rephrase it
 
also - just make an interface and assert the body as this interface
 
If Cat extends Animal and animal has a run() method then i should be able to cast Animal or Cat to Animal to call run()
 
5:53 PM
no, that's not how variance works :)
if Cat is a subclass of Animal, and Animal has a run method, you can:
 
@1.21gigawatts TS doesn't downcast like that. You'd be calling the run method on the current instance whatever its current type is. The type assertion only changes how the compiler type checks it. Not what it is.
 
1. construct an Animal, check for it to be assignable to Animal (invariance)
2. construct a Cat, check for it to be assignable to Animal (covariance - Cat is a subclass of Animal)
 
@VLAZ yes that's what i want
it's complaining about an object that should have properties on it
 
Should have or does have? If it does have them, you can use a type guard to narrow the type.
 
@OlegValteriswithUkraine cat is a subclass of animal and should inherit all the members of animal
but if i have a method that accepts type Animal then I can pass in Cat , Dog if they both accept Animal type
 
5:59 PM
correct, but your situation is different
 
@VLAZ I've updated my post. I think maybe I might have the wrong type because it says body is a stream
same class names
 
see, you assert as object - it is a very generic type. It does not have a string index signature
 
@1.21gigawatts There is an issue with downcasting, thought. It's not safe. Consider this:
const foo: Animal = new Dog();
const bar: Cat = foo downcast_to Cat;
(the downcast_to is a fictional operator)
 
so... while VLAZ is busy with variance:
 
Is there a Node.js Request object?
 
6:05 PM
OK, my bad. I didn't check the question, I was just going off chat. ^ Oleg is right. Essentially object is not what you think it is. It doesn't allow arbitrary properties.
 
asserting as Object also won't work as it is not "class of object", it represents an instance of ObjectConstructor in the type system
 
And is there a expressjs Request object?
 
What you describe is any or just Record<PropertyKey, any>
 
I thought TS supported casting though?
 
there is no casting, that's the thing
 
6:06 PM
var mynumber = Number(jsonobject.age);
 
it's not casting - it's calling a function Number (which doubles as a constructor and a normal function) over jsonobject.age
 
@1.21gigawatts No. as is type assertion. Different thing - as I said, it only tells the compiler to verify this differently. There is no actual difference at runtime. a = "hello" as unknown as number will allow you to call a.toFixed() but then error out at runtime, as it's still a string, not a number. It's just type checked as if it was a number.
 
an important thing to remember when entering TypeScript's type system: leave behind any notion of how things work in nominal type systems
 
Playground Link - look at the generated code on the right. Also run it. You get "string" logged twice. Because it's never anything else.
 
the main thing here, @1.21gigawatts, is that your problem is not with variance (well, not entirely), you are just asserting body to be of type that doesn't have an index signature. Remember - TypeScript checks by shape
 
6:14 PM
i guess so
time to go back to typescript school
 
just check out how basic types are defined in terms of shape. Thinking that object is a dictionary is a common misunderstanding. If you want to type a dictionary, the type you are looking for is Record
 
And Record will transpile to JS object?
 
no, nothing transpiles :) Well, apart from enums and namespaces
type system is isolated from runtime
@1.21gigawatts yes, Express provides a type definition for Request
2
it's also generic, so you can set your type for its body
 
@1.21gigawatts github.com/microsoft/TypeScript/wiki/FAQ#what-is-type-erasure the type system is only a compiletime artefact. It does not get transpiled into anything, it's just removed. The compiler uses it to verify if your code handles the correct things. If you need a number in a function, do you pass a number to a function. That sort of things. But after checking all this, it removes the typing and gives you JS code that is not verified to work without mismatching types.
Well, except if you have any or any type assertions that will mislead the compiler to what's really happening.
 
ok thank you for clarifying that
so in my case, the compiler is indeed getting nodejs native Request confused with expressjs Request
 
6:23 PM
you can tell it your incoming request contains type x object all you want, but when it actually comes in the code interpreting it isn't going to check that it does
 
well, not exactly - it gets the type of Request from lib.dom.d.ts, which is a built-in set of type declarations. What you are actually getting is the type of Request from Fetch API, @1.21gigawatts
 
indeed
in my server.ts I have this:
 
of note: you got a horrible answer there
 
app.post("/oage", function (request: Request, response: Response, next: any) {
  var name: string = request.body.name.toLowerCase();// no errors
 
never assert as any - that just disables all checks
 
6:27 PM
in that function i call this:
var responder = new Responder();
responder.process(request, response, next);
 
@1.21gigawatts body field has any type, that's why there are no errors
 
In responder I have this:
import express from "express";
import { Request } from "express";

export {};

export class Responder {
   async process(request: Request, response: Response, next: any) {
         var form: object = request.body;
         var parser: string = form.name.toLowerCase();
 
what is {any}??
 
var parser: string = form.name.toLowerCase() // property not found errors on this line
@OlegValteriswithUkraine typo. i was trying different types. i've updated it
 
well, you just said that form is of type object
object does not have an index signature
hence, the error
 
6:31 PM
i have an expressjs app that i want to break out the response to a different class
in the server.ts no problems, but in the class it's getting those errors
 
var form: object = request.body;
 
are these different?
var o: object
var o = {}
 
one never being initialized at runtime aside, not really
both result in an empty object as far as the compiler is concerned
you told the compiler form is of type object. It doesn't have an index signature. Hence, the compiler knows nothing about no name or whatever
you didn't tell the compiler form is assignable to anything that is a subtype of object, you told it is an object
 
@1.21gigawatts Yes: Playground Link
object just means "not a primitive". But that's about it. While {} has different semantics. Which make it pretty much useless, honestly. It describes an object but no properties for it. Due to structural integrity, everything is assignable, since extra properties are ignored. In practice {} is pretty much always a problem.
And object I may have used once or twice but isn't really useful, either. It's rare I want "non-primitive" vs something a lot more specific.
 
to add to @VLAZ, {} in terms of type system is, indeed, the most wide type possible (anything goes, no shape). However, there is another meaning to {}: completely empty object type (invoked when, for example, you do = {}).
 
6:44 PM
so should i use any then if I want to have something like a json object?
 
var json = {};
json.success = true
json.message = "Everythings fine down here"
 
@OlegValteriswithUkraine Nah, it doesn't enforce the object to be empty. let x: {}; x = {a: 1, b: true, c: "hello" } It requires at least an empty object. It only enforces the emptyness with excess property checks but at that point - why are you even declaring something that will only ever be one thing anyway?
@1.21gigawatts Record<string, any> will be the least of what I'd expect to see there.
But you might also consider a proper type for it { success: boolean, message: string }
 
@VLAZ sorry, I wasn't clear - I explicitly meant the difference between let x: {} = {} and let x = {}
@1.21gigawatts nope
 
@OlegValteriswithUkraine Yeah. But the let x = {} just gets {} as a type implicitly. Which still is useless, as it doesn't allow you adding more things as x.foo = "bar". Still a useless type, even if implicit. Ergo, pretty much always it's an error.
 
6:48 PM
@VLAZ precisely, no argument there
var json: Record<string, unknown> = {};
json.success = true
json.message = "Everythings fine down here"
 
IIRC, the type {} can only rarely be of use in a generic when it's T extends {} or something like that.
 
and that's also a dubious use of it
 
Also agreed.
I think I came across maybe one time that was useful. Vaguely useful.
 
I've seen some real-world libraries use it as a substitute for any in generic types (T = {}), but that's also horrible
 
@OlegValteriswithUkraine Well, less horrible than using any, I guess. It should also provide somewhat useful compiler errors if it turns out you try to use a specific thing off T.
It's not great but it can be worse.
Well, and it's leveraging the thing I said that it's almost always an error - you'd get an error if you don't supply the generic.
 
6:54 PM
@VLAZ yeah, but it's better to use T = unknown here: same effect, less mind-boggling
 
Probably.
 
btw, the library I am referencing is Knex :)
 
Typescript in vscode sometimes shows code hinting, auto complete and so on. i know that i've sometimes had to include a "typings" download. does vscode typescript NOT do code complete if it doesn't have types download?
 
ofc. VSC has a TypeScript language service built-in. It comes with 2 standard libs: DOM and Node (unless they got excluded by your project, but that's a different story). How do you expect the compiler to know types it doesn't have? :)
 
7:11 PM
@OlegValteriswithUkraine don't asdocs or jsdocs give type information?
/**
 * Does a thing
 * param {Number} param1
*/
 
@1.21gigawatts they do. For what is known to the compiler. And unless you, well, provided those types, how would it know about them?
 
ok i see
 
Number is a built-in type (comes from lib.dom.d.ts)
also, the JSDoc is completely wrong
/**
 * @param {number} param1
 */
Number is a type of an instance of NumberConstructor, not a number
 
7:25 PM
for primitives -> always use the lowercase version
number, string, boolean
 
7:56 PM
@Maybe Please don't post unformatted code - use the up arrow to edit your post, then hit Ctrl + K to format the code in that post. See the faq. You have 25 seconds to edit and format your message properly before it will be removed. Please separate code blocks from your actual question. Put your question in 1 message and then your code in a 2nd and format it.
For posting large code blocks, use a paste site like like gist.github.com, hastebin.com, pastie.org or a demo site like jsbin.com
1 message moved to Trash can
@Maybe Please don't post unformatted code - use the up arrow to edit your post, then hit Ctrl + K to format the code in that post. See the faq. You have 25 seconds to edit and format your message properly before it will be removed. Please separate code blocks from your actual question. Put your question in 1 message and then your code in a 2nd and format it.
For posting large code blocks, use a paste site like like gist.github.com, hastebin.com, pastie.org or a demo site like jsbin.com
1 message moved to Trash can
 
Hi. I'm trying to understand how a string.split works in javascript and would like some help.
I have this code
const ss =`1000
2000
3000

4000

5000`;

let a = ss.split('\n')
Splitting on a new line once gives me this result
[
'1000', '2000',
'3000', '',
'4000', '',
'5000'
]
I'm trying to find out why splitting on a new line twice introduces new lines into the final result
[ '1000\n2000\n3000', '4000', '5000' ]
The final result looks like some magical new lines have appeared which is really confusing
 
and how are we supposed to know what "splitting on a new line twice" means if you don't provide the code?
 
Sorry. I thought I added the code. This is the code to split on a new line twice
const ss =`1000
2000
3000

4000

5000`;

let a = ss.split('\n\n')
 
you asked it to split on points where two linefeeds appear, of course it would not split the part where there is only one single linefeed
 
That makes perfect sense. I didn't actually think about it in that way
Thank you
 
8:08 PM
well, now you do :) if you pass a string parameter instead of regular expression, it just finds whatever matches exactly
 
:) So so clear. Basically we are telling split to leave lines with a single new line alone and only focus on places with 2 new lines appearing consecutively
 
 
3 hours later…
10:46 PM
I'm reading a post that Typescript uses d.ts files to get type information
"Intellisense for JavaScript libraries and frameworks is powered by TypeScript type declaration files (with the .d.ts extension). These files have the data types of parameters and functions, allowing VS Code to provide a rich intellisense experience."
But a few years ago I wrote a library that used reflection to get this information manually
What I'm saying is it should be possible to get this information to provide some intellisense even if d.ts isn't provided
Even is no type data is available you can infer the types just by parsing the javascript
If I create a class:
class Person {
   constructor() { name = ""; age = 0 }
   run() { }
}
I should still be able to use reflection to assist with code completion
 
@1.21gigawatts Please don't post unformatted code - use the up arrow to edit your post, then hit Ctrl + K to format the code in that post. See the faq. You have 25 seconds to edit and format your message properly before it will be removed. Please separate code blocks from your actual question. Put your question in 1 message and then your code in a 2nd and format it.
1 message moved to Trash can
 
var type = Person.constructor.name;
var properties = [];
var intellisenseInfo:
for (var property in Person) {
   properties.push(property);
}
intellisenseInfo.type = type
intellisenseInfo.properties = properties
 
11:25 PM
but no one asked me
so oh WELL!
 

« first day (4434 days earlier)      last day (512 days later) »