Skip to content Skip to sidebar Skip to footer

Can You Define String Length In Typescript Interfaces?

I have a struct like so: struct tTest{ char foo [1+1]; char bar [64]; }; In TypesScript I have export interface tTest{ foo: string; bar: string; } Is there a way to add

Solution 1:

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:

interfacetTest {
    foo: string;
}

classtTestImplementationimplementstTest {
    private _foo: string;

    getfoo(): string {
        returnthis._foo;
    }

    setfoo(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.

Solution 2:

You can't force the length of an array in Typescript, as you can't in javascript. Let's say we have a class tTest as following:

classtTest{
       foo = newArray<string>(2);
};

As you can see, we have defined an array of string with length 2, with this syntax we can restrict the type of values we can put inside our array:

let t = newtTest();
console.log('lenght before initialization' +  t.foo.length);

for(var i = 0; i < t.foo.length; i++){
    console.log(t.foo[i]); 
}

t.foo[0] = 'p';
t.foo[1] = 'q';
//t.foo[2] = 3; // you can't do this
t.foo[2] = '3'; // but you can do thisconsole.log('length after initialization' +  t.foo.length);

for(var i = 0; i < t.foo.length; i++){
    console.log(t.foo[i]); 
}

In this manner we can't put a number value inside your array, but we can't limit the number of values you can put inside.

Playground

Post a Comment for "Can You Define String Length In Typescript Interfaces?"