ShintoTuna
ShintoTuna

Reputation: 3787

TypeScript literal type generator

I am trying to create an action generator that would return correct typings. So I have the following code:

const createAsyncActionWithTypes = (prefix: string, name: string) => [
    `@${prefix}/${name}_REQUEST`,
    `@${prefix}/${name}_SUCCESS`,
    `@${prefix}/${name}_FAILURE`,
  ] as const;

const requestPersonActions = createAsyncActionWithTypes('person', 'GET_PERSON');

This function makes requestPersonActions be of the following type:

const requestPersonActions: readonly [
  `@${string}/${string}_REQUEST`, 
  `@${string}/${string}_SUCCESS`, 
  `@${string}/${string}_FAILURE`
]

What I want is for createAsyncActionWithTypes function to generate the following type:

const requestPersonActions: readonly [
  `@person/GET_PERSON_REQUEST`, 
  `@person/GET_PERSON_SUCCESS`, 
  `@person/GET_PERSON_FAILURE`
]

Is it possible?

Upvotes: 1

Views: 67

Answers (1)

Guerric P
Guerric P

Reputation: 31815

You have to use generics

const createAsyncActionWithTypes = <T extends string, U extends string>(prefix: T, name: U) => [
    `@${prefix}/${name}_REQUEST`,
    `@${prefix}/${name}_SUCCESS`,
    `@${prefix}/${name}_FAILURE`,
  ] as const;

const requestPersonActions = createAsyncActionWithTypes('person', 'GET_PERSON');

TypeScript playground

Upvotes: 2

Related Questions