How can Angular know what class to Inject if typescript's types is not interpreted at run time?

Viewed 76

When we inject a dependency in a component, like this:

export class AppComponent {
  constructor(private myService: MyService) {}
}

...................

@Injectable({
  providedIn: "root",
})
export class MyService {
  constructor() {}
}

If, in typescript, types don't exist at runtime, how can angular knows that the parameter my Service needs to receive an instance of MyService ???

Edit:

giving a more concrete problem to solve:

class Dependency {}

class Foo {
  constructor(dependency: Dependency) {}
}

type Prototype<T> = new (...args: unknown[]) => T;

function InversionOfControl<T>(Class: Prototype<T>): T {
  /// injects all dependencies of Class and returns a instance of it
}

const foo = InversionOfControl(Foo);

How can I, with only typescript and regular javascript, at run time, create this InversionOfControl function.

1 Answers

Types don't exist at runtime, but a class is an actual object at runtime. Note that an interface is not a runtime object, and therefore cannot be used as an injection token.

Related