A
arktype14mo ago
OnkelTem

Using existing enum/const to build a type

Hi folks. I'm very new to arktype so maybe I'm asking something very simple. I have a pseudo enum in a third-party module I import. This const is defined as:
export declare const VoiceId: {
readonly Aditi: "Aditi";
readonly Adriano: "Adriano";
readonly Amy: "Amy";
// ...
export declare const VoiceId: {
readonly Aditi: "Aditi";
readonly Adriano: "Adriano";
readonly Amy: "Amy";
// ...
How can I build an ark type from it?
3 Replies
OnkelTem
OnkelTemOP14mo ago
const optionsSchema = type({
voiceId: // ...?
})
const optionsSchema = type({
voiceId: // ...?
})
Dimava
Dimava14mo ago
In alpha it'd be narrow(string, s=> !!VoiceId[s]) as Type<VoiceId>
enum OpCode { A, B, C }

function EnumType<
EnumObject extends Record<string, any>,
EnumType extends EnumObject[keyof EnumObject] = EnumObject[keyof EnumObject],
>(
Enum: EnumObject,
) {
return narrow(
'number',
(val: number): val is EnumType => { return Object.hasOwn(Enum, val) },
)
}
EnumType(OpCode)
enum OpCode { A, B, C }

function EnumType<
EnumObject extends Record<string, any>,
EnumType extends EnumObject[keyof EnumObject] = EnumObject[keyof EnumObject],
>(
Enum: EnumObject,
) {
return narrow(
'number',
(val: number): val is EnumType => { return Object.hasOwn(Enum, val) },
)
}
EnumType(OpCode)
(Copy-paste this one, its pro incorrect)
OnkelTem
OnkelTemOP14mo ago
Thank you
export const inputSchema2 = type({
voiceId: narrow('string', (val: string): val is VoiceId => Object.values(VoiceId).includes(val as VoiceId)),
});
export const inputSchema2 = type({
voiceId: narrow('string', (val: string): val is VoiceId => Object.values(VoiceId).includes(val as VoiceId)),
});
Want results from more Discord servers?
Add your server