Typescript Array.filter返回类型

时间:2016-08-27 14:54:31

标签: arrays typescript

let _fiveElems: [Value, Value, Value, Value, Value]
let _threeElems: [Value, Value, Value]
_threeElems = _fiveElems.filter( // some code that will filter down to three elements )

如何避免出现此编译错误?:

  

类型'Value []'不能分配给'[Value,Value,Value]'。

我可以将_threeElems的类型设置为Value[],但我知道它会返回三个元素,因此感觉不对。

2 个答案:

答案 0 :(得分:0)

TypeScript是强类型的,您对返回值的了解实际上并不重要。 filter通常可以返回变长数组,因此您必须遵守并将其返回值赋给类型Value[]的变量。 在索引数组期间,您可以执行任何操作,因此如果您确定有3个元素,则可以将它们分配给_threeElems数组。

强烈打字实际上是许多人喜欢TypeScript的事情。

答案 1 :(得分:0)

您可以使用一个检查数组长度的函数,并在运行时进行不安全的转换:

function safeArrayCast<T>(arr: T[]) : [T, T, T]{
  if (arr.length !== 3) {
    throw new Error("Array is not length of 3");
  }
  return <any>arr;
}

let _fiveElems: [Value, Value, Value, Value, Value];

let _threeElems: [Value, Value, Value];

_threeElems = safeArrayCast(_fiveElems.filter(predicate)); 

或者,如果你真的确定过滤器会返回3个元素,你可以减少额外的检查:

_threeElems = <any>_fiveElems.filter(predicate);

但请记住,使用这些不安全的演员阵容基本上会破坏你的类型安全!