0

I have some type like this

type ActionType = 'TypeA' | 'TypeB' | 'TypeC' | 'TypeD';

I want myActionType is a string, and satisfy it is one of the ActionType or a series of ActionType join with ','

const myActionType = "TypeA";
// or
const myActionType = "TypeB,TypeC,TypeA";

How to write the type to limit it

hec9527
  • 61
  • 1
  • 7
  • Is there a maximum length of the string? If there is no maximum length, then this is not possible without a helper function. – kelsny Nov 03 '22 at 03:27
  • @caTS: Oh? I believe you but I would have thought there would be an answer like `type ActionTypes = ActionType | (ActionType + ',' + ActionTypes);` – JSmart523 Nov 03 '22 at 04:05
  • 1
    @JSmart523 See for yourself: https://tsplay.dev/N5zJZm – kelsny Nov 03 '22 at 04:13

1 Answers1

0

First you need to define a generic type using conditional and recursive logic.

type MyCommaSeparatedType<T,K> = 
    T extends `${infer R1},${infer R2}` ? 
        R1 extends K ? 
        `${R1},${MyCommaSeparatedType<R2,K>}` : never : T extends K ? 
            T : never;

Then use this type as type of the argument in a helper function.

const MyCommaSeparatedFunction = <T,K extends ActionType = ActionType>(value: MyCommaSeparatedType<T,K>) => value

Now you can use this function to achieve what you intended.

Examples:

const value1 = MyCommaSeparatedFunction("TypeA")   
//value1 type is  "TypeA"

const value2 = MyCommaSeparatedFunction("TypeB,TypeA,TypeC")   
//value2  type is "TypeB,TypeA,TypeC"

const value3 = MyCommaSeparatedFunction("TypeC$TypeA")    
// value3 type is never
mahooresorkh
  • 1,361
  • 2
  • 8
  • 16
  • perhaps,you have misunderstood the question. I want compose `ActionType` as a new Type to limit a string. the string is satisfied one of the ActionType or a series of ActionType join with ',' ```ts type NewActionType = SomeWayToCompose; ``` – hec9527 Nov 08 '22 at 04:02