0
votes

I am making a generic function to check if a generic object has property given by an array of strings. To be more specific:

const staticStrings = ['name', 'age', 'address', 'photoUrl'...];
const genObject = {name: 'John Doe', bar: 'Biz'...}

Not all the foo strings are keys of bar, bar can have more keys than foo. Normally in JS I would implement something like this:

// This will render a component with value of genObject[ss] or null
 const renderStaticStrings = (staticStrings) => (genObject) => {
    return staticStrings.map((ss) => {
      return genObject.hasOwnProperty(ss) ? (
        genObject[ss]
      ) : null;
    });
  };

With Typescript I am having some trouble saying that the object should be a generic object, and that the array of string (staticStrings) could contains keys of the object. What I have tried:

  const renderStaticStrings = <T extends Object, K extends keyof T>(staticStrings: K[]) => (genObject: T) => {
    return staticStrings.map((ss) => {
      return genObject.hasOwnProperty(ss) ? genObject[ss] : null;
    });
  };

implementation:

renderStaticStrings(staticStrings)(completeProfile?.profile)}

Error: Argument of type 'string[]' is not assignable to parameter of type '(keyof Object)[]'. Type 'string' is not assignable to type 'keyof Object'

Any idea? Thanks

1

1 Answers

1
votes

I don't believe it is necessary to use generics here. Try this:

const renderStaticStrings = (staticStrings: string[]) => (genObject: Record<string, any>) => {
    return staticStrings.map((ss) => {
      return genObject.hasOwnProperty(ss) ? genObject[ss] : null;
    });
  };

const staticStrings = ['name', 'age', 'address', 'photoUrl'];
const genObject = {name: 'John Doe', bar: 'Biz'}

renderStaticStrings(staticStrings)(genObject);