Learn about how Functions work in TypeScript.
#Generics: How to allow either T or T[] but disallow T|T[] in a generic data structure?
30 messages · Page 1 of 1 (latest)
seems like the reverse of this is what you're looking for
so overloads could help with this
although of course T could be an array already unless you prevent it with T extends number | string or whatever
in what situation is this relevant/necessary to separate T from T[] for stringifications though?
i feel like you aren't actually giving the full situation, are you recieving multiple parameters?
Preview:```ts
class ToString<T> {
run(val: any) {
return val.toString()
}
}
const sys = new ToString<number | number[]>() // i want this to complain
let a = sys.run(1)
let b = sys.run([1])
console.log(a, b, a === b) // i dont want this```
You can choose specific lines to embed by selecting them before copying the link.
that's not really how it works
that's also kinda not a great pattern
what is this supposed to be for
const a = new ToString<number>().run(1);
// a = "1"
const b = new ToString<number[]>().run([1]);
// b = "1"
i really have no idea what you're trying to achieve here
there is, but that's not what generics are for
im confused, Sets already support arbitrary types
uh it does support objects though
they're compared by reference as they should
this is js lol not python
this just isn't a pattern used in js
i feel like you're missing the point of what im saying
js doesn't use objects by value, ts isn't designed with that in mind
and js ecosystem, weird types, yada yada, you've probably heard that before
ts allows types that don't work in other languages becuase of the js it's built on
when did i say anything about that
I get the feeling you're trying to be helpful, so thanks for that
on mobile now so can't test, but if you insist;
a conditional type could probably work, something along the lines of T has U[] ? T has U ? never : T : T
the 2 checks would be with [T] to avoid distributive conditionals, extends, infer
i honestly have no idea how it'd actually look though
i mean, see how convoluted it already is lol
It's ok if you don't have the answer
although, you'd of course need a ton more checks if you actually want it to work as a set
actually it'd be way more convoluted than i said, since number|number[][] would also have to fail
or string|number
or string with anything
or objects with a toString with anything
strings maybe wouldn't be so bad with [string] extends [T]