0

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'] = 'fb.com/yungsilva'
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

c69
  • 19,951
  • 7
  • 52
  • 82
Yung Silva
  • 1,324
  • 4
  • 20
  • 40
  • You cannot define types dynamically at runtime because TypeScript's type checking only occurs at compile time. You can defined the type of `typed` as `{ [key: string]: any }` but that's it. – Heretic Monkey May 17 '21 at 18:54

2 Answers2

0

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.

Yuval
  • 1,202
  • 10
  • 15
0

TypeScript is about type checking ahead of runtime. Its purpose is to check the code consistency with itself and the third party library it uses, before running it. TypeScript won't be able to assign a type depending on the actual data, because it simply doesn't exist anymore at run time. When you write will be a totally different and random structure that means you're using plain JavaScript and its dynamic nature, so if your data never has common parts, just don't type it at all (or as any).

Guerric P
  • 30,447
  • 6
  • 48
  • 86