DEV Community

Cover image for TypeScript - Como pegar uma string no seu Literal Types
Rafael Thayto
Rafael Thayto

Posted on • Edited on • Originally published at thayto.com

3

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

Originalmente postado em https://thayto.com dia 24 de Julho de 2023.

Photo by Karina Vorozheeva on Unsplash

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay