#Generate JSON from type

19 messages · Page 1 of 1 (latest)

lunar shoal
#

Hi, Using the types helpers like Parameters and ReturnType we can extract types from function parameters and return values. For example:

declare function f1(arg: { a: number; b: string }): void;

// Extract the parameters type
type FunctParams = Parameters<typeof f1>;
// [arg: { a: number; b: string; }]  // I need to read this

Could be possible to generate a json from FunctParams type? I mean without creating an instance of it

Any hints?

waxen delta
#

you can't generate values from types. so no

#

(at least not with what you get out of the box with typescript. there are third-party packages that use the TS API and/or compiler plugins to let you do stuff like this)

lunar shoal
#

Do you remember by any chance the name of any of those libraries?

waxen delta
#

i haven't personally used any of these, so can't speak to how good they are

#

you could also consider asking #ts-discussion and/or #random and/or #compiler-internals-and-api for recommendations

lunar shoal
#

I want to extract the types from a function to define an OpenAI function tool

#

Thanks for your help, I will check those projects out

waxen delta
#

you could consider going the other direction, which shouldn't require any extra tools: write the function specification as a const in the format that OpenAI wants it and then derive a function type from it

#

IIRC OpenAI uses JSON schema for this?

lunar shoal
#

Yes, OpenAI uses JSON. I could do what you suggest, but was trying to automate the process of generate the JSON function specification. I was able to do it in Python for functions, but I also needed for TypeScript

#

ts-morph looks promising, thanks

waxen delta
#

i double checked the docs since it's been a bit since i last looked at them

lunar shoal
#

I'm now back on my desk so I will check both

#

thanks again for your time

waxen delta
#

no problem