Skip to content

Extract a string array of union type from Type.Object keys #405

Answered by sinclairzx81
dephiros asked this question in Q&A
Discussion options

You must be logged in to vote

@dephiros Hi, you can try the following.

TypeScript Link Here

import { Type, Static, TSchema, UnionToTuple, TypeGuard } from '@sinclair/typebox'

// -------------------------------------------------------------------
// ObjectKeys
// -------------------------------------------------------------------
export type TStringKeys<T extends TSchema> = UnionToTuple<keyof Static<T>>

export function StringKeys<T extends TSchema>(schema: T): TStringKeys<T> {
  const keyOf: TSchema = Type.KeyOf(schema)
  const keys = TypeGuard.TUnion(keyOf)   ? keyOf.anyOf.map(literal => literal.const) :
               TypeGuard.TLiteral(keyOf) ? [keyOf.const] : []
  return keys as TStringKeys<T>
}

// -------------…

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@sinclairzx81
Comment options

Answer selected by dephiros
@dephiros
Comment options

@sinclairzx81
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants