Skip to content

Allow to remove keys from index typeΒ #51952

Closed
@Fuzzyma

Description

@Fuzzyma

Suggestion

πŸ” Search Terms

index type, omit keys

βœ… Viability 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. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

It is not possible to create a type, that has an index type + properties of a different type:

type A {
  [key: string]: number;
  foo: string
} // error

However, this case is not unsual and should be considered.
To achive that, it is needed to remove certain keys from the index.
In the definition above, this could simply be done by removing all defined keys (in this caseonly "foo") from the index automatically.

Removing keys from the index is also useful if you wanna add attributes with different type:

type A = Record<string, number>
type B = Omit<A, "foo"> & { foo: string }>

We could even go as far as making this work:

type A {
  [key: Extract<string, "foo">]: number;
  foo: string
}

A differen way of doing this without as much possibilities is to allow for negated matches in string literals:

type A {
  [key: `!foo${string}`]: number;
  foo: string;
}

(a similar issue for that example is here: #49867)

πŸ“ƒ Motivating Example

I guess I cramped all infos into the summary, I am sorry

πŸ’» Use Cases

Atm, mixing index types with other types is almost impossible. If you know, that you get an object that has certain typed values but also know that ONE keys is always set and different, you cannot type this properly atm because you cant have an index type + a different other key.

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