Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 544
mesqueeb Avatar asked Mar 18 '20 04:03

mesqueeb


People also ask

How do you escape a string literal?

String literal syntax Use the escape sequence \n to represent a new-line character as part of the string. Use the escape sequence \\ to represent a backslash character as part of the string. You can represent a single quotation mark symbol either by itself or with the escape sequence \' .

How do you use string literal in TypeScript?

Hence, you can treat a variable that has a string literal type like a variable of type string . You can access properties, call methods, and use operators, just as you would with regular strings: const eventName: "click" | "mouseover" = "click"; eventName. length; // 5 eventName.

What is string literal type in TypeScript?

The string literal type allows you to specify a set of possible string values for a variable, only those string values can be assigned to a variable. TypeScript throws a compile-time error if one tries to assign a value to the variable that isn't defined by the string literal type.

What characters must enclose a string literal?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string. You must always prefix wide-string literals with the letter L.


Video Answer


1 Answers

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

type MyStringLiteral = 'A' | 'B' | 'C'

type AorB = Exclude<MyStringLiteral, 'C'>
like image 124
mesqueeb Avatar answered Oct 19 '22 22:10

mesqueeb