2

For sane reasons, I need to have an object that has functions as key in an object, e.g:

function a() {}
function b() {}

const obj = {
  [a]: b
}

The reason for this is that I want to map the values of function a to function b and be able to remember and remove mappings again.

Now I wonder how to write typings for this in TypeScript. If I do

type MapFunctions = { [key: Function]: Function };

I will get the error

An index signature parameter type must be 'string' or 'number'.ts(1023)

But how would I write a type for this?

5
  • 1
    Those reasons are not sane and what you're trying is impossible. Commented Jul 16, 2019 at 9:47
  • Agreeing with @ritaj, if you look into what index type you have for your property [a], it's being converted to a string and doesn't remain a Function: console.log(typeof Object.keys(obj)[0] === 'string');. Your approach does not work in Javascript, and giving it a type declaration does not change that. Commented Jul 16, 2019 at 9:57
  • @ritaj first of all it is definitely possible, try this in your browser: const a = () => {}; const obj = {[a]: "val"}; console.log(obj[a]); second of all, can you elaborate on why you believe this is not sane? Commented Jul 16, 2019 at 10:24
  • @fjc thank you for your insight, I did not know the functions will bne stringified! Commented Jul 16, 2019 at 10:25
  • that is typescript question... the question is how to typescript follow the signature of a & b functions when they updated Commented Jul 22, 2020 at 8:07

1 Answer 1

5

An object can't take a function reference as the key, but you can use a Map which can take a function as a key

function a() {}
function b() {}

const map = new Map<() => void, () => void>();

map.set(a, b);

map.get(a)();
Sign up to request clarification or add additional context in comments.

1 Comment

that is typescript question... the question is how to typescript follow the signature of a & b functions when they updated

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.