0

Is it possible to get only the number keys as an type?

export const messageTypes = {
  ABLEHNUNG_ECON: {
    56: {
      message: "Zählpunkt nicht gefunden",
      event: function () {},
    },
    181: {
      message: "Gemeinschafts-ID nicht vorhanden",
      event: function () {},
    },
  },
  ZUSTIMMUNG_ECON: {
    175: {
      message: "Zustimmung erteilt",
      event: function () {},
    },
  },
  ANTWORT_ECON: {
    99: {
      message: "Meldung erhalten",
      event: function () {},
    },
  },
  ABSCHLUSS_ECON: {
    message: "Abschluss erhalten",
    event: async function (userId: string) {
      await sendNotification(userId, this.message);
    },
  },
};

If i do type MessageT = typeof messageTypes i get the whole object, but is it somehow possible to get only the numbers?

Result should be: type ResponseCodesT = 56 | 181 | 175 | 99

2
  • ABSCHLUSS_ECON doesn't have any numeric key inside it, is this intentional or typo? Commented Jun 27, 2022 at 11:12
  • @Cerberus its not typo, its intentional. However, i could technically add an random code in this case, but i first ask if its possible now how it is Commented Jun 27, 2022 at 11:15

1 Answer 1

2

It is possible using a little keyof trick (Typescript: keyof typeof union between object and primitive is always never):

export const messageTypes = {
  ABLEHNUNG_ECON: {
    56: {
      message: "Zählpunkt nicht gefunden",
      event: function () {},
    },
    181: {
      message: "Gemeinschafts-ID nicht vorhanden",
      event: function () {},
    },
  },
  ZUSTIMMUNG_ECON: {
    175: {
      message: "Zustimmung erteilt",
      event: function () {},
    },
  },
  ANTWORT_ECON: {
    99: {
      message: "Meldung erhalten",
      event: function () {},
    },
  },
};

type AllUnionMemberKeys<T> = T extends any ? keyof T : never;
type MessageCode = AllUnionMemberKeys<(typeof messageTypes)[keyof typeof messageTypes]>;

// type MessageCode = 56 | 181 | 175 | 99

Playground

I intentionally left out ABSCHLUSS_ECON as an exercise for the reader :) (Hint: the union will include message and event).

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

2 Comments

Could you explain why is AllUnionMemberKeys required ?
@MatthieuRiegler see the linked question for details. in short, keyof X | Y produces never if X and Y have no properties in common, while the conditional helps because it distributes the union first and then unions the keys.

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.