Siema mam taki maly problem odnosnie cwiczenia jakim jest wlasna implementacja metody array reduce w typescript. O ile w czystym js nawet nie jest to takie trudne (plus duzo jest materialu na yt) to w TS mi wywala dziwne bledy plus nie do konca jestem przekonany czy moja implementacja jest w 100% ok. tutaj przedstawiam moja implementacje w TS.
const myReduce = <T,R> (array:T[], callback:(accumulator:T, currentValue:T, index:number, array:T[] )=>T, initialValue?: R) =>{
let accumulator;
if (initialValue === undefined) {
accumulator = array[0];
} else {
accumulator = initialValue;
}
for(const index in array){
const item = array[index];
accumulator = callback(accumulator as T, item as T, +index, array)
}
return accumulator
}
gdy chce uporzatkowac troche kod to wpadlem na pomysl zeby stworzyc typ dla argumentow callbacku wiec zrobilem cos takiego :
type CallbackReduce<T,R> = (accumulator:T, currentValue:T, index:number, array:T[]) => R
ale wywala mi wtedy blad: przy accumulator
Type 'R' is not assignable to type 'R & null'.
Type 'R' is not assignable to type 'null'.ts(2322)
blueprint.ts(5, 21): This type parameter might need an `extends null` constraint.
blueprint.ts(5, 21): This type parameter might need an `extends R & null` constraint.
blueprint.ts(5, 21): This type parameter might need an `extends T | (R & ({} | null)) | undefined` constraint.
let accumulator: T | (R & ({} | null)) | undefined _kursywa_ ```
i generalnie jesli nie dodam initial value w moim myReduce to liczy mi np. sume o 1 wiecej niz jest faktycznie. Prosze o pomoc wydaje mi sie ze jestem blisko ale no utknalem ;p