Skip to content

Don't allow a Record keyed by a template literal type to be assigned to a type without a compatible index signatureΒ #61782

Closed as not planned
@tylerc

Description

@tylerc

πŸ” Search Terms

record index indexed type template literal type assignable assignability

βœ… Viability Checklist

⭐ Suggestion

Types like Record<`id_${string}`, { foo: 'bar' }> are common in our apps, but it is surprisingly easy to accidentally assign an object with an incompatible type. It would help catch errors (especially during refactoring) if a compatible index signature type was required for assignment.

πŸ“ƒ Motivating Example

During a recent refactoring, a previously infallible function was changed to return a list of warnings along with its result. One of the use sites was missed during the refactoring, resulting in a bug that it feels like TypeScript could've caught:

type Mapping = Record<`id_${string}`, { foo: 'bar' }>;

// Previously, this just returned a Mapping directly
function computeMappingAndWarnings(): {
  mapping: Mapping,
  warnings: string[]
} {
  return {
    mapping: {},
    warnings: []
  };
}

const result: Mapping = computeMappingAndWarnings(); // πŸ› Expected error here, meant to assign .mapping field.

Playground Link

πŸ’» Use Cases

  1. What do you want to use this for? - Safer use of Record types when keyed by template literal types.
  2. What shortcomings exist with current approaches? - We could use a Map instead, but Maps don't survive the roundtrip from JSON and back, and so can be harder to use when crossing the network boundary.
  3. What workarounds are you using in the meantime? - For now we're converting to Maps where we can, and are viewing existing Records with suspicion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions