Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Proposed type tweak to improve use of Record instance in TypeScript code #341

Closed
@andrewdavey

Description

@andrewdavey

When using records in TypeScript, it would be nice to define an interface declaring the properties. We can then access those properties, instead of going through the get method. This cleans up code and catches typos at compile time.

interface Customer extends Map<string, any> {
  id: string;
  name: string;
}

var CustomerRecord = Immutable.Record<Customer>({ id: "", name: "" });

var customer1 = new CustomerRecord({ id: "1", name: "John" });

alert(customer1.id);
customer1 = customer1.set("name", "Jon"); // Can still use as a Map
alert(customer1.wrong); // Compile-time error here

To achieve this, the Record function and interface declaration need to be made generic:

export module Record {
  export interface Class<T extends Map<string, any>> {
    new (): T;
    new (values: { [key: string]: any }): T;
    new (values: Iterable<string, any>): T; // deprecated
  }
}

export function Record<T extends Map<string, any>>(
  defaultValues: { [key: string]: any }, name?: string
  ): Record.Class<T>;

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions