Instantiation Expressions Pin Type Arguments
Pin generic type arguments to a class reference without calling the constructor, so helper aliases inherit strict item types and wrong members fail compilation.
Code
class Registry<T> {
items: T[] = [];
add(item: T): this {
this.items.push(item);
return this;
}
}
// An instantiation expression applies type arguments without calling new
const StringRegistry = Registry<string>;
const names = new StringRegistry().add('ada').add('grace');
console.log('names:', names.items.join(', '));
// StringRegistry.add only accepts strings; add(42) would fail compilation
console.log('all strings:', names.items.every((i) => typeof i === 'string'));
// The same generic class reuses cleanly with a different type argument
const NumberRegistry = Registry<number>;
console.log('numbers:', new NumberRegistry().add(7).add(9).items.length);Output
Captured from a sandboxed run of this snippet in the build pipeline.
names: ada, grace
all strings: true
numbers: 2How this snippet works
const StringRegistry = Registry<string> applies the type argument without new; the derived alias’s add then only accepts strings, and the same class re-instantiates as NumberRegistry with no re-declaration.
The demo data lives in module-level bindings: StringRegistry, names, NumberRegistry.
Applying it
Three labeled lines close the demo: names: ada, grace from the chained add calls, all strings: true from the typeof check, and numbers: 2 from the freshly pinned NumberRegistry.
Statements that matter
const names = new StringRegistry().add('ada').add('grace');
const StringRegistry = Registry<string>;
const NumberRegistry = Registry<number>;
Interactive Tools for This Topic
FAQ
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `StringRegistry`, `names`, `NumberRegistry`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.