#declare a variable type in a function

18 messages ยท Page 1 of 1 (latest)

open cipher
#

Hey guys, does anyone know how I could type a variable in a function ? I am using alpinejs with bun and I am running into this issue a lot.
Here is what my code looks like:

const Container = () =>{
  return <p x-data={pData.toString()} x-show={showP.toString()}></p>
}

const pData = () => ({
  shouldBeVisible: true,
})

const showP = () => {
  return shouldBeVisible; //<== type error here
}

This code works just fine, however how could I type the variable shouldBeVisible to a boolean ?
I know I can use the declare keyword but that's for global use.

Any ideas ๐Ÿ˜€ ?

dusty narwhal
#

Alpine really works like this? You pass a string form of a function?

#

I don't know enough about alpine to help. This is not normal TypeScript I think

open cipher
#

yeah it works just fine, you're meant to use it inside of string but because I am working with bun I can just extract those strings into function and call .toString(). The good thing about this is that I get the lsp support and type error. Which I don't get if I was working with plain string

dusty narwhal
#

So are you getting an error now?

#

Yeah you'd get an undefined variable error

open cipher
#

no it's working just fine. I do get a typescript error but not runtime.

dusty narwhal
#

That's what I mean

#

I would honestly give up on trying to use that with TypeScript at all

#

Maybe search for any guides/solutions to using Alpine with TS

#

I feel like you would need a custom compiler/typechecker that could read and work with Alpine's approach.

#

But I do get results for Alpine + TS, so maybe I just don't know how it works together.

open cipher
#

yeah I agree it's definitly a hacky way of using alpine ๐Ÿ˜… I was just playing around anyway so nothing serious.

dusty narwhal
#

Best I can do is this

left peakBOT
#
sandiford#0

Preview:```ts
const Container = (() => {
let shouldBeVisible: boolean = true

const pData = () => ({
shouldBeVisible: true,
})

const showP = () => {
return shouldBeVisible //<== type error here
}

const Container = () => {
return (
<p
x-data={pData.toString()}
x-show={showP.toString()}
></p>
)
}
return Container
})()```

dusty narwhal
#

should have been : boolean not : true

open cipher
#

that makes sense, thanks for looking into it ๐Ÿ˜€

dusty narwhal
#

Welcome, have fun with this nightmare system haha ๐Ÿ™‚