After compiling source code from TypeScript to JavaScript, type annotations are removed and it becomes impossible to verify the type of a variable at runtime.
Despite this limitation, there exist TypeScript libraries that alter their behavior based on the type annotations of class properties. For instance, when defining TypeORM entities, developers may create something like:
@Entity()
class MyEntity extends BaseEntity {
@Field()
public id: number // automatically determines int database type
@Field()
public description: string // automatically infers varchar or text database type
@Field()
public image: string | null // unable to infer correct type, causing an error
}
We can observe similar functionality in typedi (passing the correct reference through constructors), type-graphql (constructing the GraphQL schema with accurate GraphQL types), and so forth. While it's understandable when a function needs to be passed through a decorator or related structure, how do these libraries deduce types solely from type annotations?