0

I'm a Typescript new learner, and I wonder how to achieve the following type? Is it possible or not? any help would be appreciated, thank you.

type step = 'STEP_1' | 'STEP_2' | 'STEP_3' | 'STEP_4';

// Q: how to define this type, to achieve below effect?
type stepsNoDuplicatedType = ??  

// let ts check ok:
 const steps: stepsNoDuplicatedType = ['STEP_1' , 'STEP_2', 'STEP_3' , 'STEP_4'];
 const stepsFinished: stepsNoDuplicatedType = ['STEP_1' , 'STEP_2'];

// let ts check fail, due to 'STEP_1' duplicated:
 const steps: stepsNoDuplicatedType = ['STEP_1' , 'STEP_2', 'STEP_3' , 'STEP_4', 'STEP_1'];
 const stepsFinished: stepsNoDuplicatedType = ['STEP_1' , 'STEP_2', 'STEP_1'];
  • You seem to be mixing the concept of values and types. The values in the array are a run-time thing and cannot be specified by a type. – super Apr 22 '22 at 14:36
  • Thanks for the reply, @super. if there is a statement like the following code, is it possible to check and warn in compile time? in my opinion, the TS static syntax check will work, right? ``` const stepsFinished: stepsNoDuplicatedType = ['STEP_1' , 'STEP_2', 'STEP_1']; ``` – Bo Yuan Apr 24 '22 at 01:13
  • Yes. The accepted answer to the duplicate question shows a good example on how to detect duplicate values in the array. That should be a good start, then just make sure all values are also a type union with the different steps. – super Apr 24 '22 at 18:26

0 Answers0