Why does typescript not accept `text() && text().length === x` in solid-start?

Is anyone aware why typescript complains about
text() && text().length === 6
text() && text().length === 6
in a project with the tsconfig.json that comes with the solid-start template? (E.g. typescript complains I should use text()?.length but it didn't in other projects with solid.js) I swear I had solid.js applications where the ts compiler correctly deduced that I checked that text() is non-falsy? EDIT: "typescript": "^4.9.4"
6 Replies
apollo79
apollo792y ago
The problem here is, that a function can return something different for each call, so ts won't allow this.
Bersaelor
BersaelorOP2y ago
ok, so probably the ts compiler is just broken in my other ts project yeah, gotta use text()?.length === 6 then
apollo79
apollo792y ago
There are multiple solutions to this afaik: 1. You can assign the result to a variable and check it 2. You can use the non-null-assertion operator ! 3. You can write a check function with return type T is ... Or yes, you can use ?. 👍
Bersaelor
BersaelorOP2y ago
1. You can assign the result to a variable and check it
Yeah, thats what I usually do, it's just so verbose compared to other environments. In swift for example we can do
if let value = someOptional() {
use(value)
}
if let value = someOptional() {
use(value)
}
where in ts I have to do
const value = someOptional()
if (value) {
use(value);
}
const value = someOptional()
if (value) {
use(value);
}
apollo79
apollo792y ago
Yes, that is true But I see no problem with using the non-null-assertion operator if you checked it before Or writing a check function if it feels less verbose
bigmistqke
bigmistqke2y ago
I have this utility function I use sometimes when(signal()).then(signal => ...)
Want results from more Discord servers?
Add your server