Search code examples
typescripttypestemplate-literals

How To Get Difference Between Two Template Literal Types In Typescript?


Given the following example snippet:

const firstName = `Abraham` as const;
const fullName = `${firstName}Lincoln` as const;

type FullName = typeof fullName;
type FirstName = typeof firstName;

// type LastName = "Lincoln"

The goal is to get access to the LastName type without writing it out, considering that the firstName is known and that the lastName is already contained inside the fullName.

I've tried two similar approaches, none of which was fruitful.


Solution

  • const firstName = `Abraham` as const;
    const fullName = `${firstName}Lincoln` as const;
    
    type FullName = typeof fullName;
    type FirstName = typeof firstName;
    
    
    type Difference<T extends string, U extends string> = 
      // T is the common part
      // Scd is the difference we want to retrieve
      U extends `${T}${infer Scd}` ? Scd : never
    
    type Result = Difference<FirstName, FullName> // Lincoln
    

    Playground