你能在 TypeScript 接口中定义字符串长度吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39117089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you define string length in TypeScript interfaces?
提问by Faigjaz
I have a struct like so:
我有一个像这样的结构:
struct tTest{
char foo [1+1];
char bar [64];
};
In TypesScript I have
在 TypesScript 我有
export interface tTest{
foo: string;
bar: string;
}
Is there a way to add [64] and [1+1] to the type?
有没有办法将 [64] 和 [1+1] 添加到类型中?
采纳答案by Nitzan Tomer
As the comments say: js/ts don't support the char type and there's no way to declare array/string lengths.
正如评论所说:js/ts 不支持 char 类型,并且无法声明数组/字符串长度。
You can enforce that using a setter though:
不过,您可以使用 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 += " ";
}
}
}
(操场上的代码)
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.
您需要有一个实际的类,因为接口缺乏实现并且无法在编译过程中幸存下来。
我只是添加了空格以获得确切的长度,但您可以更改它以满足您的需要。
回答by alessandro
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:
您不能在 Typescript 中强制设置数组的长度,就像在 javascript 中一样。
假设我们有一个类 tTest 如下:
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:
如您所见,我们定义了一个长度为 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]);
}
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.
通过这种方式,我们不能在数组中放入数字值,但不能限制可以放入的值的数量。