3

I want to make an array, which will specify, which strings will index properties inside object and that object properties only contain functions.

What I do understand, is that I can create union type from just array:

My working case is a reducer action (instruction) in React reducer (but it can be used elsewhere):

const InstructionsArray = [
    'HANDLE_BUTTON_CONVERT_INPUT',
    'HANDLE_CHECKBOX_CONVERT_ON_INPUT',
    'HANDLE_CHECKBOX_DISPLAY_TAGS',
    'HANDLE_TEXTAREA_INPUT',
    'HANDLE_RUNTIME'
] as const;

Then I have type object with property:

instruction: typeof InstructionsArray[number]

Of course, normal array would allow us to use any string as indexes, but since we casted it as const, it now only allows for the strings, we specified in array.

What I actually want, is to have an object, which will have some property names as string and all properties will have value of function. I would like to specify only those property names (string), but as every value will be a function, I would not like to specify it more than once, so it can be taken as granted.

Current code looks like that:

const changersLabels = [
    'inventory',
    'quest'
] as const;

But the 'same' way does not work on object like that:

keyboardRouter(changers: {[key:typeof changersLabels[number]:Function]}) {

    //some stuff

}

What am I doing wrong and is that even possible?

1 Answer 1

5

Looks like you just want a mapped type where the keys are typeof changersLabels[number] and the properties are all Function:

function keyboardRouter(changers: { [K in typeof changersLabels[number]]: Function }) {
  changers.inventory // Function
  changers.quest // Function
}

A mapped type looks a little like a type with an index signature, but that only works where the index is of type string or of type number. For other types like a union of string literals, you need a mapped type with the in operator.

Which could be slightly refactored to give a name to your keys and to use the built-in Record utility type:

type ChangersLabels = typeof changersLabels[number];
function keyboardRouter2(changers: Record<ChangersLabels, Function>) {
  changers.inventory // Function
  changers.quest // Function
}

Playground link to code

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.