Issue
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' )
Solution
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) {}
Answered By - Tobias S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.