Search code examples
typescriptstring-literals

How to Omit a string in a String Literal in TypeScript


I know we can use Omit<> to type a certain object without specific props. I was hoping we could also use this for string literals:

type possibleStrings = 'A' | 'B' | 'C'

type AorB = Omit<possibleStrings, 'C'>

But when trying to use something like this in a function for its params, I get this error:

Type 'Pick' cannot be used as an index type.


Solution

  • You can use Exclude for omitting a single string in a String Literal.

    type MyStringLiteral = 'A' | 'B' | 'C'
    
    type AorB = Exclude<MyStringLiteral, 'C'>