francisrstokes / construct-js

🛠️A library for creating byte level data structures.
MIT License
1.37k stars 29 forks source link

Typing the added properties #36

Open Xample opened 1 year ago

Xample commented 1 year ago

Hello, I'm wondering if you would consider typing the added fields in TS, I just made an experiment here below as an example:

In this way, we can write the following code

const struct = new Struct()
.field("hello", "world")
.field("foo", "bar")
.build();

struct.hello // okay -> world
struct.foo // okay -> bar
struct.nope // error

This is just to show a possible way of adding properties by chaining to a type using ts.

Version TS>=5

Equivalent code for Version TS<5

Xample commented 1 year ago

Oh and nesting structs works as well

const struct = new Struct()
.field("hello", "World")
.field("foo", "bar")
.build();

struct.hello
struct.foo

const struct2 = new Struct()
.field("hello", "World")
.field("struct", struct)
.build();

struct2.struct.foo // okay
francisrstokes commented 1 year ago

Hey @Xample - thanks for taking the time to open this issue. I agree that this would be a really nice addition. The way the code is setup and used, I can imagine that there would be some divergences from the example you linked, but I'm sure its something that could be solved. Definitely open to ideas and contributions relating to this if you're interested in working on it.

Xample commented 1 year ago

good, well right now I'm not using construct-js, I used it in a POC a few years ago, and I always thought about improving the typing as below. Note that, there are other possible way to ensure we do keep the typing without even having to create a new object (as in my example). I'm really flooded and really don't have any free time for this contribution, but if I have to use it again, I will give a try.