Skip to content

String literal type for use in single-property mapped types #25019

@magnushiie

Description

@magnushiie

Search Terms

  • string literal indexer mapped type
  • string literal
  • mapped type

Suggestion

Add a new type (stringliteral in the example below) that would be a super-type of all string literals, but not unions.

Use Cases

Mapped types are great when building an object out of another object, or when starting with object literals with constant property names. There currently doesn't seem to be an option to build out an object typed with mapped types with variable property names.

Examples

We can build an algebra of base object construction and composition functions.

Note: this example composes plain objects, but the actual motivation is to have more complex structures that internally maintain a typed object and the algebra allows composing them in various ways.

const singlePropertyObject = <N extends string, V>(n: N, v: V): { [P in N]: V } =>
  ({ [n]: v } as { [P in N]: V }); // note: cast required
const compose = <O1 extends object, O2 extends object>(o1: O1, o2: O2) =>
  Object.assign({}, o1, o2);

const oa = singlePropertyObject('a', 'v1'); // { a: string; }
const ob = singlePropertyObject('b', 'v1'); // { b: string; }
const oab = compose(oa, ob);

But this is unsafe - singlePropertyObject can be used to create arbitrary objects with non-optional fields but without value without type errors:

const oaUnsafe = singlePropertyObject<'a' | 'b', string>('a', 'v1'); // { a: string; b: string; }

The current behavior is of course correct, in that { [n]: V } can be implicitly cast only to { [P in N]?: V } - if N is a union, the other members of the union don't have a value set.

What could help is to narrow the generic argument N to a single string literal to prevent unions:

const singlePropertyObject = <N extends stringliteral, V>(n: N, v: V): { [P in N]: V } =>
  ({ [n]: v }); // note: no cast required anymore

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions