Question:
String literal type containing an arbitrary number of substring literal types?

Problem

If I have string literal types Hello and World, I can write a string literal type that contains both of them as


type ContainsSubstrings = `${string}Hello${string}World${string}` | `${string}World${string}Hello${string}`;


Is it possible to achieve this for an arbitrary number of substrings in an arbitrary order?


I want to enforce that an SQL string contains all parameterized keys from an object.


edit: To clarify, I am wondering if a generic type is possible that can take an arbitrary list of strings and enforce that they are all substrings of a string literal type.


Solution

You could use intersection types that says it must match both string patterns.


type X = `${string}a${string}` & `${string}b${string}`;


// Valid

let x: X = 'xaxbx';

x = 'xbxax';


// Invalid

x = 'xbx';


Suggested blogs:

>Fix: Strange compilation error with Typescript and Angular

>What if the property 'X' does not exist on type 'FastifyContext<unknown>'?

>How to get the type of a class property's getter/setter in TypeScript?

>How to assign multiple const variables in a single declaration in TypeScript?

>Type inference with 'as const' IN TypeScript

>Typescript Return argument: Tuple type or passed to rest parameter warning?

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?


Nisha Patel

Nisha Patel

Submit
0 Answers