Home > OS >  TypeScript: sort array of objects by variabke key where key might be optional
TypeScript: sort array of objects by variabke key where key might be optional

Time:11-27

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

CodePudding user response:

You need to save a[prop] and b[prop] into variables:

testContainer.test.sort((a, b) => {
  const aProp = a[prop];
  const bProp = b[prop];
  if (aProp === undefined || bProp === undefined) return 0;
  return aProp > bProp ? -1 : bProp > aProp? 1 : 0;
});

From here:

This isn't really about TS2532 specifically but about type narrowing in general--TS doesn't treat any check involving obj[key] as a type guard unless key is a literal.

  • Related