#Any way to save TS interface as a plain variable?

5 messages · Page 1 of 1 (latest)

stable jolt
#

I want to create a form builder, where you can pass it a generic type, and it will create the appropriate inputs, but I'm not sure if it's possible in TS to reference a type as a variable.

type User = {
   name?: string;
   email: string;
   age: string;
}

// item can be null if we're creating a new record, truthy if we're editing
const createForm<T> = ( itemToEdit?: T ) => {
   // somehow save T as a variable (could be a stringified version that i could parse?)
   // so we can determine which fields, and their types to render, which are required, etc.
}

Iterating over itemToEdit doesn't work, bc some keys may be missing from the object, and this needs to be used for creation as well. Thanks!

simple portal
#

typescript types don't exist at runtime. during compilation they are removed entirely from your code. there's no way to derive a value from a type (but you can go the other way around)

supple berry
#

There's also https://deepkit.io/ which does provide runtime type information and will let you do the above

#

but it comes with runtime overhead