liveBook · Manning

Type inference

As explained in Modern Angular

Type inference is the determination of static types from expressions and their surrounding usage without explicit type annotations.

Type inference determines useful static types from declarations and usage, reducing annotations while exposing mismatches early. Angular’s inject function infers the type associated with an InjectionToken, avoiding the wordier and less secure @Inject pattern. A misspelled property can otherwise leave the token correctly injected while the property type is wrong. section 3.2.3

Reactive forms provide another practical use. Since Angular 14, form controls infer the structure of their values instead of defaulting to any. The inferred value remains Partial because fields may be absent, even when validators are present; after checking validity, code may narrow or cast the value. Templates still catch mismatched control names, such as using email when the control is misspelled emali. section 4.3.2

Application-wide constants and typed employee forms

Define a root-provided Constants InjectionToken for shared values such as dateFormat, then inject it with inject(Constants) so the property type follows the token. In an HRMS employee form, use dot notation such as form.controls.email; Angular’s inferred control type reports a misspelled control name before the template runs. section 3.2.3 section 4.3.2

Listing 3.7 Injection token for application-wide constants
import { InjectionToken } from '@angular/core';

const CONSTANTS = {  #1
    dateFormat: 'dd/MM/yyyy',
};

export const Constants = new InjectionToken('Constants', {
    factory() {
        return CONSTANTS;  #2
    },
    providedIn: 'root',  #3
});

Shows a root-provided InjectionToken whose factory returns application-wide constants, providing the typed dependency consumed through inject. section 3.2.3

How Modern Angular covers it

How deep it goes
Explains inferred token and form types, partial values, casts, dot notation, and template diagnostics, but not inference internals.
Examples
Uses application-wide date constants, inject(Constants), and an HRMS employee form whose misspelled email control triggers a template error.
What it assumes
Assumes familiarity with TypeScript types, Angular dependency injection, InjectionToken, reactive forms, validators, and templates.
What you can do after
Diagnose Angular injection and form-control mismatches earlier through inferred properties, typed values, and template checking.
How it connects
Connects type inference with Angular dependency injection, InjectionToken, TypeScript, reactive forms, validators, and templates.

Also explained in

Compare how 16 books explain type inference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern Angular. The section links point to the parts of the book it draws on.