zecik123 zecik123 - 1 month ago 18x
TypeScript Question

Typescript Array.filter return type

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

How can I avoid getting this compiler error?:

Type 'Value[]' is not assignable to type '[Value, Value, Value]'.

I can set the type of _threeElems to Value[], but I know it will return three elements so it doesn't feel right.


You could use a function that checks the array length and does an unsafe cast at runtime:

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

Or, if you are REALLY sure that the filter will return 3 elements, you can cut that extra check:

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

But remember, using these unsafe casts will basically break your typesafety!