Skip to content

Instantly share code, notes, and snippets.

@theaungmyatmoe
Created January 17, 2023 15:29
Show Gist options
  • Save theaungmyatmoe/299b2e9950c1870c15b7b6bcb479da5b to your computer and use it in GitHub Desktop.
Save theaungmyatmoe/299b2e9950c1870c15b7b6bcb479da5b to your computer and use it in GitHub Desktop.

Making immutable type with const in ts-v5

Playground Link

const makeRoles = <const T extends {role:string, flages:any}>(roles: T[]) => {
    return {
        findFlags<TRole extends T['role']>(roleToFind:TRole){
                return roles.find(role => role.role === roleToFind)?.flages as Extract<T, {role:TRole}>['flages']
        }
    }
}

const {findFlags} = makeRoles([
    {role:"admin", flages: {
        canCreatePost:true,
        canDeletePost:true,
          canReadPost:true,
    }},
    {role:"user", flages: {
        canCreatePost:false,
        canDeletePost:true,
        canReadPost:true,
    }},
])

const flags = findFlags("user")
//      ^?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment