Home > OS >  Substring of a string type TypeScript
Substring of a string type TypeScript

Time:08-03

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' ) 

CodePudding user response:

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) {}

Playground

  • Related