Substring of a string type TypeScript

Viewed 202

Is it possible to make a value passed to a function be a partial string (i.e., a substring) in TypeScript

Something along the lines of this?

function transform( str: Substring<'Hello world'> ) {
    // ...
}

And when I then call the function I can pass a substring of that string

transform( 'world' );
// or
transform( 'Hello' );
// or
transform( 'ello' ); // Is valid because it exists in hello
// or
transform( 'orl' ); // Is valid because it exists in world

// Is not valid, altough individual letters exists 
// they are not in the right order
transform( 'hlowrld' ) 
1 Answers

You could certainly make the function generic and check if T is a substring of Hello world via template literal types.

function transform<
  T extends string
>(str: "Hello World" extends `${string}${T}${string}` ? T : never) {}

transform('World')
transform('Hello')
transform('ello')
transform('orl')

transform('hlowrld') 
//         ^^^^^^^ Argument of type 'string' is not assignable to parameter of type 'never'

This can also be converted into a reusable utility type.

type Substring<
  S extends string, 
  T extends string
> = S extends `${string}${T}${string}` ? T : never

function transform<
  T extends string
>(str: Substring<"Hello World", T>) {}

Playground

Related