TypeScript complaining even the code is correct?

type TradeSummary = Record<string, {
symbol: string;
datetime: string;
realizedPnl: number;
commission: number;
}>;


const closedTrades = Object.values(transactions.reduce((acc: TradeSummary, curr) => {
const { symbol, realizedPnl, commission } = curr.info;
const year = curr.datetime.slice(0, 4);
const month = curr.datetime.slice(5, 7);
const day = curr.datetime.slice(8, 10);
const datetime = `${year}-${month}-${day}`;

const key = `${symbol}_${datetime}`;

if (!acc[key]) {
acc[key] = { symbol, datetime, realizedPnl: 0, commission: 0};
}

acc[key].realizedPnl += parseFloat(realizedPnl);
acc[key].commission += parseFloat(commission);

acc[key].realizedPnl = parseFloat(acc[key].realizedPnl.toFixed(2))
acc[key].commission = parseFloat(acc[key].commission.toFixed(2));

return acc;
}, {}));
type TradeSummary = Record<string, {
symbol: string;
datetime: string;
realizedPnl: number;
commission: number;
}>;


const closedTrades = Object.values(transactions.reduce((acc: TradeSummary, curr) => {
const { symbol, realizedPnl, commission } = curr.info;
const year = curr.datetime.slice(0, 4);
const month = curr.datetime.slice(5, 7);
const day = curr.datetime.slice(8, 10);
const datetime = `${year}-${month}-${day}`;

const key = `${symbol}_${datetime}`;

if (!acc[key]) {
acc[key] = { symbol, datetime, realizedPnl: 0, commission: 0};
}

acc[key].realizedPnl += parseFloat(realizedPnl);
acc[key].commission += parseFloat(commission);

acc[key].realizedPnl = parseFloat(acc[key].realizedPnl.toFixed(2))
acc[key].commission = parseFloat(acc[key].commission.toFixed(2));

return acc;
}, {}));
So even I am initializing the object TypeScript keeps yelling acc[key] might be undefined. What am I missing?
3 Replies
Benjamin
Benjamin•17mo ago
It is because it is unsafe. I assume you're using a Map, which is a good thing, you should take the advantage of has(), get(), set()... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
Map - JavaScript | MDN
The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
Benjamin
Benjamin•17mo ago
I don't have the context of your use case, but maybe groupBy would be interesting: https://lodash.com/docs/4.17.15#groupBy By the way, don't forget to specify typescript when you write code in Discord so it gets syntax highlighted 😉
ray1sx
ray1sxOP•17mo ago
Oh I see. I could not figure it out and did not occur to me using the has(), get() ... I will try to solve this way. Thank you!
Want results from more Discord servers?
Add your server