Hone logo
Hone
Problems

Implementing a Generic StartsWith Type in TypeScript

Many programming languages provide built-in functionalities to check if a string starts with a specific substring. In TypeScript, we can leverage the power of mapped types and conditional types to create a robust and type-safe way to achieve this for string literal types. This challenge will guide you through implementing a generic type that checks if a literal string type begins with another literal string type.

Problem Description

Your task is to create a TypeScript generic conditional type called StartsWith<T, Prefix>. This type should take two generic type arguments:

  1. T: The string literal type to check.
  2. Prefix: The string literal type that we want to see if T starts with.

The StartsWith type should return true if the string literal type T begins with the string literal type Prefix, and false otherwise.

Key Requirements:

  • The type must be generic.
  • It must handle string literal types correctly.
  • It should return a boolean literal type (true or false).
  • Consider edge cases like an empty prefix or a prefix longer than the string.

Expected Behavior:

  • StartsWith<'hello world', 'hello'> should resolve to true.
  • StartsWith<'hello world', 'world'> should resolve to false.
  • StartsWith<'abc', 'abcd'> should resolve to false.
  • StartsWith<'abc', ''> should resolve to true.
  • StartsWith<'', '' should resolve to true.

Examples

Example 1:

type StartsWithHello = StartsWith<'hello world', 'hello'>;
// Expected Output: true

Example 2:

type StartsWithWorld = StartsWith<'hello world', 'world'>;
// Expected Output: false

Example 3:

type StartsWithLongerPrefix = StartsWith<'abc', 'abcd'>;
// Expected Output: false

Example 4:

type StartsWithEmptyPrefix = StartsWith<'abc', ''>;
// Expected Output: true

Constraints

  • The types T and Prefix are expected to be string literal types.
  • The solution should leverage TypeScript's type system features, specifically conditional types and potentially template literal types or string manipulation within types.
  • No runtime JavaScript code is required; this is purely a type-level operation.

Notes

Think about how you can decompose string literal types in TypeScript. Template literal types offer powerful ways to manipulate strings at the type level. Consider what happens when the Prefix is an empty string or when T is shorter than Prefix. You might need to use string manipulation functions available within TypeScript's type system, such as string extends ${infer Start}${infer Rest}``, to help you.

Loading editor...
typescript