Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Pick for literal type

Tags:

typescript

Is there a way to Pick (or any other solution) from literal type for connection to main Roles interface?

Reason for this, if i in future will change or delete something in Roles, i can see where i need to change/delete it to.

Playground.

type Roles = 'admin' | 'user' | 'guest'

// no connection to Roles
type ApiRoute = { roles: 'admin' | 'user' }

// how to?
type ApiRouteWithCheck = { roles: Pick<Roles, 'admin' | 'user'> }
like image 337
ZiiMakc Avatar asked Dec 29 '25 06:12

ZiiMakc


1 Answers

You can either Exclude the values you don't want:

type ApiRoute = { roles: Exclude<Roles, 'guest'> };

or Extract the values you do:

type ApiRoute = { roles: Extract<Roles, 'admin' | 'user'> };
like image 76
jonrsharpe Avatar answered Dec 31 '25 00:12

jonrsharpe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!