i have an Type and an Array of Objects of this Type. "Unfortunally" some keys in that Type are optional. That breaks my dynamic sort function. How can I make this work? I won't call it with those optional keys so it would be OK if the function does not or does wrongly sort in that case.
export type Test = {
adam: string;
eve?: string;
};
export type Container = {
test: Array<Test>;
};
const testContainer = {} as Container;
export function sortTest(prop: keyof Test) {
testContainer.test.sort((a, b) => {
if (a[prop] === undefined || b[prop] === undefined || !(prop in b) || !(prop in a)) {
return 0;
} else {
return a[prop] > b[prop] ? -1 : b[prop] > a[prop] ? 1 : 0;
}
});
}
As you can see, i tried 2 different approaches to make sure prop is part of a and b. Both don't work. I'm always getting ts 2532 - Object is possibly 'undefined' at the actual sorting line.
Link to Playground