DEV Community

Rafael Thayto
Rafael Thayto

Posted on

TypeScript - Como pegar uma string no seu Literal Types

Salve, salve devs seniors.

Não vou enrolar nada. Basicamente é só você utilizar o Utility Type Extract do próprio TypeScript e boa! Por exemplo:

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

// tmj!
Enter fullscreen mode Exit fullscreen mode

link do TS Playground

espero que ajude alguém!

(OBS: esse post foi escrito em no máximo 10 minutos)

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

Top comments (0)