typescriptutilitiestypestutorial

TypeScript - How to Extract a String from Your Literal Types

Rafael Thayto
TypeScript - How to Extract a String from Your Literal Types

Hey there, senior devs.

I won't beat around the bush. Basically just use TypeScript's Utility Type Extract and that's it! For example:

type CatNames = 'Garfield' | 'Yoru' | 'Yuki' | 'Fluffy' | 'Lady' | 'Lucky'

type MyCatNames = Extract<CatNames, 'Yoru' | 'Yuki'>
// |-> Extract these two `literal types` from CatNames `literal type`

type Cat = {
  age: number
  name: CatNames
}

function getMyCat(age: number, name: MyCatNames): Cat {
  // |--> only show 'Yoru' and
  //                'Yuki'
  return {
    age,
    name,
  } as Cat
}

const myCat1 = getMyCat(1, 'Yoru')
const myCat2 = getMyCat(1, 'Yuki')

const otherCat: Cat = {
  age: 3,
  name: 'Garfield',
}
const otherCatWithMyCatName: Cat = {
  age: 5,
  name: 'Yoru',
}

// cheers!

TS Playground link

hope this helps someone!

(NOTE: this post was written in 10 minutes max)

my links: https://thayto.com/linktree

Photo by Karina Vorozheeva on Unsplash

TypeScript - How to Extract a String from Your Literal Types - Rafael Thayto