Having issues with generics and 'nested' interfaces when working with ReadonlyArray
. Is there a way to utilize the filterList
function without losing the type for the list
parameter?
interface INumber {
value: number
}
interface IState {
readonly numbers: ReadonlyArray<INumber>
}
var state: IState = {
numbers: [{ value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }]
}
function filterList<T>(list: T) {
return list.filter(x => x.value > 2);
}
// Error: Property 'filter' does not exist on type 'T'.
const res = filterList(state.numbers);
If we attempt to modify the filterList
function as shown below, it will fail due to the use of ReadonlyArray.
function filterList(list: INumber[]) {...}
// Error: Argument of type 'ReadonlyArray<INumber>' is not assignable
// to parameter of type 'INumber[]'. Property 'pop' is missing in
// type 'ReadonlyArray<INumber>'.
const res = filterList(state.numbers);
How should this situation be best handled? Appreciate any insights!