Lesser-Known TypeScript Features Worth Learning
Explore seven lesser-known TypeScript features, from const type parameters and NoInfer to assertion functions and verbatimModuleSyntax, with versions and code examples.
Seven TypeScript features that many experienced developers still don’t use are const type parameters (5.0), NoInfer (5.4), assertion functions (3.7), labeled tuple elements (4.0), variance annotations (4.7), the accessor keyword (4.9), and import type combined with verbatimModuleSyntax (3.8 and 5.0).
If you learned TypeScript around 4.x and have been busy shipping since, you probably still write as const at call sites and add extra type parameters to stop inference from widening. Newer releases give you shorter ways to do both.
This article covers each feature in turn: what it does, which version introduced it, and one short example that compiles under strict mode.
Key Takeaways
- A
consttype parameter (TypeScript 5.0) infers["/", "/users"]asreadonly ["/", "/users"]when the constraint is readonly, such asreadonly string[]. NoInfer<T>(TypeScript 5.4) stops a parameter from acting as an inference site, so a default value can’t widen the type that the other arguments establish.- An assertion function written as
asserts value is Tnarrows its argument for the rest of the scope after the call, not just inside anifblock. - Under
verbatimModuleSyntax, an import is removed only whentypeapplies to the whole statement.import { type X } from "./mod"emitsimport {} from "./mod", so the module still runs.
Advanced TypeScript Features by Version
The table lists each of the seven lesser-known TypeScript features with the version that introduced it and the developers it matters most to.
| Feature | Introduced in | Main audience |
|---|---|---|
| Assertion functions | 3.7 | App and library code |
import type | 3.8 | Build config |
| Labeled tuple elements | 4.0 | Hook and API authors |
Variance annotations (in/out) | 4.7 | Library authors |
accessor keyword | 4.9 | Decorator users |
| const type parameters | 5.0 | Generic API authors |
verbatimModuleSyntax | 5.0 | Build config |
NoInfer<T> | 5.4 | Generic API authors |
Const Type Parameters (TypeScript 5.0)
TypeScript 5.0 added the const modifier on type parameters. It makes the compiler infer array and object literals as if the caller had written as const. Callers no longer need to remember the assertion to get literal types.
Pair the const modifier with a readonly constraint if you want readonly results. With a mutable constraint such as string[], TypeScript 5.0 to 5.2 fell back to string[]. Since 5.3 the compiler infers a mutable tuple instead. The const modifier also only applies to literals written directly in the call. A variable declared earlier keeps the widened type it already had.
function defineRoutes<T extends readonly string[]>(paths: T): T { return paths; }
const a = defineRoutes(["/", "/users"]); // string[]
function defineRoutesExact<const T extends readonly string[]>(paths: T): T { return paths; }
const b = defineRoutesExact(["/", "/users"]); // readonly ["/", "/users"]
function defineRoutesMutable<const T extends string[]>(paths: T): T { return paths; }
const c = defineRoutesMutable(["/", "/users"]); // ["/", "/users"] (TS 5.3+; string[] in 5.0–5.2)
NoInfer for Controlled Inference (TypeScript 5.4)
NoInfer<T>, added in TypeScript 5.4, stops the compiler from using a given argument as an inference source. That argument is then checked against the type inferred from the other parameters, instead of widening it. Before 5.4, the usual workaround was a second type parameter constrained by the first. It worked, but it added a type parameter that appeared only once in the signature.
function createSelect<T extends string>(options: T[], initial: NoInfer<T>) {
return { options, value: initial };
}
createSelect(["draft", "published"], "draft"); // OK
createSelect(["draft", "published"], "archived");
// Error: Argument of type '"archived"' is not assignable
// to parameter of type '"draft" | "published"'.
Without NoInfer, T would widen to "draft" | "published" | "archived" and the typo would compile. The utility types reference documents it alongside Partial and Pick.
Assertion Functions (TypeScript 3.7)
An assertion function narrows its argument for the rest of the enclosing scope once it returns without throwing. That makes it a good fit for fail-fast guard clauses that don’t need a branch. A type guard (value is T) narrows only inside the conditional that calls it. An asserts value is T signature, introduced in TypeScript 3.7, narrows everything after the call.
function assertIsDefined<T>(value: T, name = "value"): asserts value is NonNullable<T> {
if (value === undefined || value === null) {
throw new Error(`${name} is not defined`);
}
}
const root = document.getElementById("app"); // HTMLElement | null
assertIsDefined(root, "#app");
root.classList.add("ready"); // root: HTMLElement
Assertion functions have one catch. If you write the helper as an arrow function assigned to an unannotated const, the call site fails with “Assertions require every name in the call target to be declared with an explicit type annotation.” Either use a function declaration or give the const an explicit type.
Labeled Tuple Elements (TypeScript 4.0)
Labeled tuple elements, added in TypeScript 4.0, let you name each position in a tuple type. The names appear in editor hovers, signature help and error messages. Tuple labels change only what editors and error messages display. They don’t change the tuple’s type, and callers can destructure the elements under any names they like. Since TypeScript 5.2, a tuple can also mix labeled and unlabeled elements.
A hook-style return type is the classic use case:
type ToggleState = [isOn: boolean, toggle: () => void];
function useToggle(initial = false): ToggleState {
let isOn = initial;
return [isOn, () => { isOn = !isOn; }];
}
const [open, toggleOpen] = useToggle(); // any names work; labels show in hovers
Variance Annotations: in and out (TypeScript 4.7)
Variance annotations, introduced in TypeScript 4.7, let you declare explicitly whether a type parameter is covariant (out), contravariant (in), or both. Variance annotations are mostly for library authors. Application code almost never needs them. The 4.7 notes present them as a way to document intent and, for deeply recursive types, to speed up type-checking. TypeScript reports an error when an annotation contradicts how the parameter is actually used, but it accepts annotations that are stricter than necessary.
interface Producer<out T> { get: () => T }
interface Consumer<in T> { accept: (value: T) => void }
interface Bad<in T> { get: () => T }
// Error: Type 'Bad<super-T>' is not assignable to type 'Bad<sub-T>'
// as implied by variance annotation.
The accessor Keyword (TypeScript 4.9)
TypeScript 4.9 added auto-accessors. You declare one like a class field but prefix it with accessor. The compiler turns it into a getter and setter pair backed by an unreachable private field. An auto-accessor therefore gives a decorator a single place to intercept both reads and writes of the field.
The example below uses the standard decorator signature from TypeScript 5.0, with types from the compiler’s built-in decorators.d.ts. It requires experimentalDecorators to be off, because legacy decorators use a different signature.
function logged<This, V>(
target: ClassAccessorDecoratorTarget<This, V>,
context: ClassAccessorDecoratorContext<This, V>
): ClassAccessorDecoratorResult<This, V> {
return {
set(value) {
console.log(`set ${String(context.name)} =`, value);
target.set.call(this, value);
},
};
}
class Settings {
@logged accessor theme = "light";
}
import type with verbatimModuleSyntax (TypeScript 3.8 and 5.0)
Under verbatimModuleSyntax, TypeScript deletes an import only when type applies to the whole statement. It emits every other import as written. The import type syntax dates back to TypeScript 3.8. The flag itself came in 5.0 and replaced importsNotUsedAsValues and preserveValueImports, which were deprecated in 5.0 and no longer exist in TypeScript 7.
{ "compilerOptions": { "verbatimModuleSyntax": true } }
import type { User } from "./api"; // erased entirely
import { fetchUser, type Post } from "./api"; // emits: import { fetchUser } from "./api";
import { type Config } from "./config"; // emits: import {} from "./config";
The third line, import { type Config }, catches people out. An inline type modifier still leaves an empty import behind, so the module is loaded and its side effects run. When you turn the flag on, any type imported without a type modifier becomes a compile error. Migrating mostly means converting type-only named imports to import type.
Related Advanced TypeScript Topics
Several topics were left out on purpose because they have their own articles:
- A Practical Guide to TypeScript’s satisfies Operator
- Understanding infer in TypeScript
- How JavaScript Finally Learned to Clean Up After Itself (the
usingkeyword) - TypeScript Best Practices for Large Projects (covers branded types)
- 5 Tips To Improve Your TypeScript Code
Conclusion
Most of these features either replace a workaround or move a check from runtime convention into the type system. const type parameters and NoInfer give generic APIs precise inference without asking callers to do extra work. Assertion functions and labeled tuples tighten everyday app code, and verbatimModuleSyntax makes emitted imports predictable. A practical first step is to enable verbatimModuleSyntax in one package, fix the type-only imports the compiler flags, and then add const to any generic that currently tells callers to append as const.
FAQs
Does verbatimModuleSyntax work in projects that emit CommonJS?
Yes, but files that emit as CommonJS must use TypeScript's CommonJS-style syntax: import fs = require('fs') for imports and export = for exports. Writing ESM import or export statements in those files is a compile error. Current releases report it as TS1295, which suggests changing the type field in package.json or adjusting your module settings. Files that emit as ESM keep normal import and export syntax.
Do I still need isolatedModules if I enable verbatimModuleSyntax?
No. The TSConfig reference sets isolatedModules to true by default whenever verbatimModuleSyntax is enabled, so its single-file transpilation checks apply automatically and you can drop the explicit entry. Those checks matter for tools like esbuild, SWC and Babel, which compile each file separately and cannot tell whether an imported name is a type or a value.
Can an assertion function be async?
No. TypeScript has no async assertion signature, so a return type like Promise<asserts value is T> is not valid. The feature has been requested in TypeScript issue 37681 but is not part of the language. The usual workaround is to await the async work first, then call a synchronous assertion function on the result, or have the async function return the validated value with a narrowed type.
Complete picture for complete understanding
Capture every clue your frontend is leaving so you can instantly get to the root cause of any issue with OpenReplay — the open-source session replay tool for developers. Self-host it in minutes, and have complete control over your customer data.
Star on GitHub12k