Faigjaz Faigjaz - 3 months ago 38
TypeScript Question

struct-like interfaces in Typescript/JS?

since I couln't find a clear answer in the interwebs, hear goes my question:

I have a "struct" like so:

struct tTest{
public:
char foo [1+1]
char bar [64]
};


Is there a way to build this in TS/JS?

I thought using interfaces is the right way:

export interface tTest{
foo: string;
bar: string
}


But there is not a way to add [64] and [1+1] to the properties, is it?
It would be awesome if there is, since I need every tTest like object to be of the same length and it would be way harder to check the length and add stuff til it has the right length. I feel like this would be really dirty.

Any ideas/help?
Thanks!

Answer

As the comments say: js/ts don't support the char type and there's no way to declare array/string lengths.

You can enforce that using a setter though:

interface tTest {
    foo: string;
}

class tTestImplementation implements tTest {
    private _foo: string;

    get foo(): string {
        return this._foo;
    }

    set foo(value: string) {
        this._foo = value;

        while (this._foo.length < 64) {
            this._foo += " ";
        }
    }
}

(code in playground)

You'll need to have an actual class as the interfaces lacks implementation and doesn't survive the compilation process.
I just added spaces to get to the exact length, but you can change that to fit your needs.