#Create new object from another object - typebox optional

1 messages · Page 1 of 1 (latest)

lost musk
#

Hello,
can you help me how i can keep object keys hints when create new object

import type { TPropertyKey, TSchema } from '@sinclair/typebox';

export const createOptional = (list: Record<TPropertyKey, TSchema>) => {
  return Object.fromEntries(Object.entries(list).map(([key, value]) => [key, Type.Optional(value)])) as Record<TPropertyKey, TOptional<TSchema>>;
}

const result = createOptional({ id: Type.String() });
indigo bobcat
#

You're probably going to want to do this: ```ts
export const createOptional = <T extends Record<TPropertyKey, TSchema>>(list: T) => {}

#

And then either remove the as Record<...> at the end, or make it as T

#

Oh the keys too, moment *

worn kilnBOT
#
mjuksel#0

Preview:```ts
import type {
TPropertyKey,
TSchema,
Type,
} from "@sinclair/typebox"
console.clear()

export const createOptional = <
T extends Record<TPropertyKey, TSchema>

(
list: T
) => {
return Object.fromEntries(
Object.entries(list).map(([key, value]) => [
key,
Type.Optional(value),
])
) as T
...```

lost musk
indigo bobcat
#

I think you need to pass in Optional in createOptional

#

I haven't really seen that library, so I dunno how it works exactly

#

Ye looks like it

lost musk
#
type Optional<T extends Record<TPropertyKey, TSchema>> = {
  [Key in keyof T]: TOptional<T[Key]>;
}
export const createOptional = <T extends Record<TPropertyKey, TSchema>>(list: T) => {
  return Object.fromEntries(Object.entries(list).map(([key, value]) => [key, Type.Optional(value)])) as Optional<T>;
}

const schema = { id: Type.String() };
const schema_optional = createOptional(schema);

const schema_id = schema.id;
const schema_optional_id = schema_optional.id;

#

it works now as i wanted it, thank you for help @indigo bobcat ❤️

indigo bobcat
#

😘 np