Skip to content

TS: How to get interface from a dynamically created object

I have a schema object that contains the typed property that starts empty.

const schema = {
  typed: {},
  // ...

schema.typed will be filled dynamically when the application starts, example

typed['name'] = 'Yung Silva'
typed['age'] = 22

in another moment

typed['facebook'] = ''
typed['whatsapp'] = 81981355509

there is no pattern, really each time the application is started it will be a totally different and random structure.

I would like to get an interface for this object that was dynamically assembled, example

type Fields = typeof schema.typed

it is possible?

is disturbing me at the beginning, at the moment to create the object dynamically, I don’t know what type to define for schema.typed


This is not possible since Typescript “checks” your types at compile time.

“The goal of TypeScript is to help catch mistakes early (before running the code, at compile time) through a type system and to make JavaScript development more efficient.” more

At runtime the code that runs is a normal (sorta) javascript code. there are several libraries (typescript-is) that can help you check types at run time, but the common use case doesn’t need them.