typescript

How to define a type that only allows a specific string literal from another type?


I have defined a string literal type and, for another type, it requires one of the string literals; however only one specific string is accepted in that instance. So now I'm wondering how I can define that.

Example:

type MyStrings = 'A' | 'B' | 'C';

// Option 1
type MyOtherType1 = {
  type: MyStrings;
  whatever: string;
}

// Option 2
type MyOtherType2 = {  
  type: 'A';
  whatever: string;
}

With Option 1, I keep the reference to the original type; with Option 2 I make sure only the correct type is passed.

Is there something where I can specify only that one string, while still referencing where the type is coming from?


Solution

  • The best way would be to Extract the member you want:

    type MyOtherType = {
      type: Extract<MyStrings, 'A'>;
      whatever: string;
    }
    
    

    That way you're still using MyStrings but, if it is subsequently updated such that 'A' is no longer a member, although the Extract itself wouldn't fail (it would just be never) anything trying to assign 'A' to type would start showing an error.

    Alternatively, depending on the specific context: