Is there a good way to use an array of fields mapped from an object into array as string literals?

So probably really simple and I am just missing something. I am trying to achieve the following:
export const SCOPES = {
user: {
can_edit: "can_edit",
},
organiser: {
can_edit: "can_edit",
},
event: {
can_edit: "can_edit",
}
} as const;

const test = Object.values(SCOPES.user).map((scope) => `'${scope}'`);

export const user = type({
"...": permissionBase,
type: "'user'",
scopes: test
});
export const SCOPES = {
user: {
can_edit: "can_edit",
},
organiser: {
can_edit: "can_edit",
},
event: {
can_edit: "can_edit",
}
} as const;

const test = Object.values(SCOPES.user).map((scope) => `'${scope}'`);

export const user = type({
"...": permissionBase,
type: "'user'",
scopes: test
});
Not sure if this is possible but I may be missing something? The issue obviously comes in that its not a as const. But trying to figure out how I can achieve something like that. In this case its supposed to be an array of those strings.
2 Replies
CodingWithLuke
CodingWithLukeOP4d ago
const UserScopes = type(Object.values(SCOPES.user).join(" | ") as `'${typeof SCOPES.user[keyof typeof SCOPES.user]}'`).array();
const UserScopes = type(Object.values(SCOPES.user).join(" | ") as `'${typeof SCOPES.user[keyof typeof SCOPES.user]}'`).array();
^ This seems to resolve type issues The above however seems to give: 'can_edit' is unresolvable
ssalbdivad
ssalbdivad3d ago
This is just an issue to do with how narrowly TS is willing to infer Object.values and .map here, not with ArkType specifically. It has to be written or cast such that when you mouse over test, you'd see something that would be a valid ArkType definition You'd need to use some complex types like unionToTuple or a utility function for extracting narrowed values to do this

Did you find this page helpful?