Is there a way in typescript define fixed size array. say, for example, in a function definition, I need to able to say
在typescript中有一种方法定义固定大小的数组。比方说,例如,在函数定义中,我需要能够说
coord: (c:any) => number[]; //how to say it is an array of size 4
can I define an interface like we define a hash map
我可以像定义哈希映射一样定义接口
//this doesn't work
interface IArray{
[number]
}
and also restrict max length to be 4.
并且还将最大长度限制为4。
3 个解决方案
#1
6
It's sort of awkward, but you can do it like this:
这有点尴尬,但你可以这样做:
interface SizeFour<T> {
0: T;
1: T;
2: T;
3: T;
}
function fn(): SizeFour<string> {
// Need to cast
return <any>['', '', '', ''];
}
var x = fn();
var a = x[0]; // a: string
var b = x[4]; // b: any; error if --noImplicitAny
#2
10
You could return a tuple instead of an array:
你可以返回一个元组而不是一个数组:
type array_of_4 = [number, number, number, number];
var myFixedLengthArray :array_of_4 = [1,2,3,4];
// the tuple can be used as an array:
console.log(myFixedLengthArray.join(','));
#3
3
Preventing someone from using an index into an array outside the bounds is not something that even C# can do. e.g. what is preventing you from doing :
防止有人在索引之外的数组中使用索引不是C#可以做的事情。例如什么阻止你做:
var index = 123;
sizeFour[index];
Or even requesting the index from the server?
甚至从服务器请求索引?
So short answer "there isn't a declarative way of preventing this if you insist on using []
"
如此简短的回答“如果你坚持使用[],就没有一种预防性的方法可以防止这种情况发生。
You could always do
你可以随时做
var bar = {
one : 'something',
two: 'somethingelse'
// etc.
}
and then only use .
i.e. bar.one
然后才使用。即bar.one
#1
6
It's sort of awkward, but you can do it like this:
这有点尴尬,但你可以这样做:
interface SizeFour<T> {
0: T;
1: T;
2: T;
3: T;
}
function fn(): SizeFour<string> {
// Need to cast
return <any>['', '', '', ''];
}
var x = fn();
var a = x[0]; // a: string
var b = x[4]; // b: any; error if --noImplicitAny
#2
10
You could return a tuple instead of an array:
你可以返回一个元组而不是一个数组:
type array_of_4 = [number, number, number, number];
var myFixedLengthArray :array_of_4 = [1,2,3,4];
// the tuple can be used as an array:
console.log(myFixedLengthArray.join(','));
#3
3
Preventing someone from using an index into an array outside the bounds is not something that even C# can do. e.g. what is preventing you from doing :
防止有人在索引之外的数组中使用索引不是C#可以做的事情。例如什么阻止你做:
var index = 123;
sizeFour[index];
Or even requesting the index from the server?
甚至从服务器请求索引?
So short answer "there isn't a declarative way of preventing this if you insist on using []
"
如此简短的回答“如果你坚持使用[],就没有一种预防性的方法可以防止这种情况发生。
You could always do
你可以随时做
var bar = {
one : 'something',
two: 'somethingelse'
// etc.
}
and then only use .
i.e. bar.one
然后才使用。即bar.one