Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 666
Faigjaz Avatar asked Aug 24 '16 07:08

Faigjaz


People also ask

How do you find the length of a string in TypeScript?

To get the length of a String in TypeScript, you can use length property of the String object. When you use the length property on the String object, it returns an integer that represents the length of the string.

Can we define method in interface TypeScript?

A TypeScript Interface can include method declarations using arrow functions or normal functions, it can also include properties and return types. The methods can have parameters or remain parameterless.


1 Answers

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.

like image 181
Nitzan Tomer Avatar answered Oct 03 '22 06:10

Nitzan Tomer