type AcceptedClass = "one" | "two" | "three";
type ClassName = `${AcceptedClass} ${ClassName}`;
const className: ClassName = "one two three";
const className2: ClassName = "two one three one three";
const className3: ClassName = "three";
const className4: ClassName = "three one two three one two";
I'd like to create type like code (below), But there's something error
Type alias 'ClassName' circularly references itself.ts(2456)
Is it not possible make that types in typescript?
CodePudding user response:
You cannot have a circular dependency when using type literals.
Think about it like this:
- TS needs replace ${ClassName} with all the possibilities that
ClassName
can take - When you use ${ClassName} inside the definition of ${ClassName} it will need to include the 1st iteration for ClassName
- This will go on for ever.
Templated types are fully extended so you cannot have an unbounded type, which you are trying to do. TS has a hard limit of 100k terms in a union type.
You could use something like this, but with limited availability:
const type ClassName = `${AcceptedClass} ${AcceptedClass} ${AcceptedClass} ${AcceptedClass}`;