Structs in TypeScript

Our example demonstrates how to define and use structs. Structs in TypeScript are represented by interfaces and classes. Here’s the complete example translated:

// Define the person interface
interface Person {
    name: string;
    age: number;
}

// Define a class that implements the person interface
class PersonClass implements Person {
    name: string;
    age: number;

    constructor(name: string) {
        this.name = name;
        // Default age set to 42
        this.age = 42;
    }
}

// Create new instances and use them
function main() {
    console.log({ name: "Bob", age: 20 });

    // Named fields initialization
    console.log({ name: "Alice", age: 30 });

    // Omitted fields default to undefined
    console.log({ name: "Fred", age: undefined });

    // Using class for struct-like functionality
    console.log(new PersonClass("Ann"));

    // Custom constructor function
    console.log(new PersonClass("Jon"));

    // Access fields using dot notation
    const s: Person = { name: "Sean", age: 50 };
    console.log(s.name);

    // Access fields through object
    const sp: Person = s;
    console.log(sp.age);

    // Mutate struct fields
    (sp as any).age = 51; // Note: Direct mutation is not typical in TypeScript
    console.log(sp.age);

    // Example of an anonymous struct type
    const dog = {
        name: "Rex",
        isGood: true
    };
    console.log(dog);
}

main();

Explanation

Struct Definition

In TypeScript, structs can be represented by interfaces or classes. An interface defines the structure, while a class can implement it and provide constructor or methods:

interface Person {
    name: string;
    age: number;
}

Constructor Function

A constructor function or class is used to initialize new instances of Person:

class PersonClass implements Person {
    name: string;
    age: number;

    constructor(name: string) {
        this.name = name;
        this.age = 42; // default age
    }
}

Instantiating Structs

You can create new instances directly:

console.log({ name: "Bob", age: 20 });
console.log({ name: "Alice", age: 30 });
console.log({ name: "Fred", age: undefined });

Or by using the class:

console.log(new PersonClass("Ann"));
console.log(new PersonClass("Jon"));

Access and Mutation

Fields in the struct-like objects can be accessed and mutated using dot notation:

const s: Person = { name: "Sean", age: 50 };
console.log(s.name);

const sp: Person = s;
console.log(sp.age);

(sp as any).age = 51; // Note that direct mutation is not typical in TypeScript
console.log(sp.age);

Anonymous Struct Type

TypeScript supports anonymous types, used in inline variable declarations:

const dog = {
    name: "Rex",
    isGood: true
};
console.log(dog);

This way, we maintain the expressiveness and idiomatic usage in TypeScript while closely following the original structure of the example.