Extract a string array of union type from Type.Object keys #405
-
Hi, I am trying to use
My attempt:
Would there be some Typescript magic(beside casting |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
@dephiros Hi, TypeBox supports TypeScript's import { Type, Static } from '@sinclair/typebox'
type T = Static<typeof T> // type T = { title: string, count: number }
const T = Type.Object({ // const T = {
title: Type.String(), // type: 'object',
count: Type.Number() // properties: {
}) // title: { type: 'string', [Symbol(TypeBox.Kind)]: 'String' },
// count: { type: 'number', [Symbol(TypeBox.Kind)]: 'Number' }
// },
// required: [ 'title', 'count' ],
// [Symbol(TypeBox.Kind)]: 'Object'
// }
type K = Static<typeof K> // type K = 'title' | 'count'
const K = Type.KeyOf(T) // const K = {
// anyOf: [
// { const: 'title', type: 'string', [Symbol(TypeBox.Kind)]: 'Literal' },
// { const: 'count', type: 'string', [Symbol(TypeBox.Kind)]: 'Literal' }
// ],
// [Symbol(TypeBox.Kind)]: 'Union'
// } If you only need the keys as a type (with no schema), you can use the following which avoids the need to prop dive through type K = keyof Static<typeof T> // just the static type Hope this helps! |
Beta Was this translation helpful? Give feedback.
-
Hi @sinclairzx81 , Thank you for the answer and it pointed me to the right direction. What I wanted is an actual array of properties key but with the union type. This is a bit clunky but produces the right result:
Though for some reasons, when I tried to extract to a helper method, Typescript is not quite happy:
|
Beta Was this translation helpful? Give feedback.
@dephiros Hi, you can try the following.
TypeScript Link Here