Public annotation choices
Concept and syntax
An exported function is available to other modules. Use an explicit parameter and return contract for public functions where consumers depend on stable types. Local implementation variables can still use inference. A declaration such as export function total(price: number): number makes a change to text output a compile-time error instead of accidentally changing the public contract. Export syntax will be studied fully in the modules chapter.
Working example
Compile standalone examples in a fresh directory with tsc --strict --target ES2022 --module commonjs --noEmitOnError main.ts, then node main.js.
export function total(price: number): number { const fee = 2; return price + fee;}console.log(total(5));Expected output (one line per log):
7Common mistake
Intentionally invalid; check this snippet separately. Do not run it.
export function total(price: number): number { return String(price + 2); }Expected compiler diagnostic: TS2322. A public number result is incompatible with a returned string. Preserve the number contract unless consumers are deliberately migrated.
Practice and recap
Write an exported numeric discount function with an explicit return annotation. Change the implementation to return text and inspect the diagnostic.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Public annotation choices — knowledge check
Check the concept, apply it to a new choice, and interpret a compiler diagnostic.
Which annotation is most useful to protect a stable exported result?
Should local implementation variables always have explicit annotations?
Which return expression preserves the public number contract?
export function total(price: number): number { return String(price + 2); }