Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I make this typescript function return strong typed array instead of string[]

I have this function that I’m trying to convert from js to ts, I thought that the type of the variable hi will be ('s'|'bb')[] but actually it’s string[]. How can I get typescript to infer K to be the keys of NewOptions?

export const getWithOverrides = <
  K extends string,
  NewOptions extends { [x in K]?: boolean },
  Overrides extends { [x in K]?: boolean }
>(
  newOptions: NewOptions,
  overrides: Overrides
): K[] =>
  (Object.keys(newOptions) as K[]).filter(key => {
    if (typeof overrides[key] === 'boolean') {
      return overrides[key];
    }
    return newOptions[key];
  });

const hi = getWithOverrides({ s: true, bb: true }, { s: true });

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can do that by removing the K type parameter, requiring that the object types extend Record<string, boolean>, and using keyof with your two object types:

export const getWithOverrides = <
    NewOptions extends Record<string, boolean>,
    Overrides extends Record<string, boolean>
>(
    newOptions: NewOptions,
    overrides: Overrides
): (keyof NewOptions | keyof Overrides)[] =>
    Object.keys(newOptions).filter((key) => {
        if (typeof overrides[key] === "boolean") {
            return overrides[key];
        }
        return newOptions[key];
    });

const hi = getWithOverrides({ s: true, bb: true }, { s: true });
//    ^? const hi: ("s" | "bb")[]

Playground example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading