3

I'm trying add getter/setter properties to a function, TypeScript doesn't complain until I'm trying access that property.

const obj:{[key:string]:string} = {
  blah: "ok",
  test: "yes"
};

const func = (a:string):void => {};

for(const key in obj)
{
  Object.defineProperty(func, key, {
    get() { return obj[key]},
    set(a:string) {
      obj[key] = a;
    }
  });
}
console.log([func]); //good, shows function and new properties
console.log(func.blah); //error TS2339: Property 'blah' does not exist on type '(a: string) => void'.

I'm trying avoid "any" and property names as type declarations.

Any tips?

3
  • 2
    obj is defined as {[key:string]:string} -- do we want to only allow accessing known properties func.blah and func.test or do we want to access any property? Basically you need to assert the type of func before you add the properties: const func = ((a:string) => {}) as ((a:string) => void) & {[key:string]:string}; Commented Feb 28, 2021 at 18:41
  • Thank you. That worked. Would you post it as a solution, so I can upvote? Commented Feb 28, 2021 at 19:50
  • Nice avatar ))))) Commented Feb 28, 2021 at 22:58

1 Answer 1

1

You need to use as to assert the type of func as something which includes the properties that you are adding.

With the index signature from obj:

const func = ((a:string) => {}) as ((a:string) => void) & {[key:string]:string};

With a dynamic type from typeof obj:

const func = ((a:string) => {}) as ((a:string) => void) & typeof obj;

With some specific set of properties (could be just blah and test instead of any string):

const func = ((a:string) => {}) as ((a:string) => void) & SomeInterface;
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.