Faigjaz
Faigjaz

Reputation: 838

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 [64] and [1+1] to the type?

Upvotes: 13

Views: 26842

Answers (2)

invernomuto
invernomuto

Reputation: 10211

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:

class tTest{
       foo = new Array<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 = new tTest();
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 this

console.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

Upvotes: 2

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

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.

Upvotes: 14

Related Questions