TypeScript 3.8: Private Fields and Top-Level Await

TypeScript 3.8 brings ECMAScript private fields and top-level await. These are significant additions that change how we write TypeScript.

Private Fields (#)

class Person {
  #name: string;  // Truly private
  
  constructor(name: string) {
    this.#name = name;
  }
  
  greet() {
    console.log(`Hello, ${this.#name}!`);
  }
}

const p = new Person("Alice");
p.greet();      // Works
p.#name;        // Error - private field
p["#name"];     // Still error - runtime private!

Private vs private

  • private: Compile-time only, accessible at runtime
  • #field: True runtime privacy, JavaScript feature

Top-Level Await

// config.ts - no async wrapper needed!
const response = await fetch('/api/config');
export const config = await response.json();

// main.ts
import { config } from './config';
console.log(config.apiUrl);  // Module waits for config

Export * as Namespace

// Re-export everything under a namespace
export * as utils from './utils';

// Usage
import { utils } from './module';
utils.helper();

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.