0

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 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

yes this works, I have tried the same solution but I though having any wans't such a good idea... can be useful in this case though
any is perfectly acceptable if you don't have a narrower type that you can use. If you know that the values of genObject will be string, you can use that. If this type varies (sometimes string, sometimes number, etc.), then you can create a generic on that type.

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.