繁体   English   中英

您可以在TypeScript接口中定义字符串长度吗?

[英]Can you define string length in TypeScript interfaces?

我有一个像这样的结构:

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

在TypesScript中,我有

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

是否可以将[64]和[1 + 1]添加到类型?

就像评论说的那样:js / ts不支持char类型,没有办法声明数组/字符串的长度。

您可以使用setter来强制执行:

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 += " ";
        }
    }
}

操场上的代码

您将需要一个实际的类,因为接口缺乏实现,并且无法在编译过程中生存。
我只是添加了空格以达到确切的长度,但是您可以根据自己的需要进行更改。

您不能像在JavaScript中那样在Typescript中强制设置数组的长度。
假设我们有一个tTest类,如下所示:

class tTest{
       foo = new Array<string>(2);
};

如您所见,我们定义了一个长度为2的字符串数组,使用这种语法我们可以限制我们可以放入数组中的值的类型:

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]); 
}

这样,我们不能在数组中放入数字值,但不能限制可以放入其中的值的数目。

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM