1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.