Skip to content

Fixed keys should not need to be a subset of dynamic keys #43057

Closed
@danielo515

Description

@danielo515

Suggestion

I think it should be possible to have fixed properties on a dictionary that doesn't need to match the type of the generic ones, or the other way round: that generic values should not be a superset of the fixed values

🔍 Search Terms

dynamic keys, static keys, mixing static and dynamic 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

So, in terms of code, I want to be able to type this:

type X = { startDate: string, [name: string]: number  }

However, typescript does not understand that the fixedKey startDate doesn't need to match the other generic key value pair, so you are forced to write it like this:

type X = { startDate: string, [name: string]: number| string }

💻 Use Cases

Adding dynamic keys to objects in javascript is quite common, and they don't need to match the type of existing keys. Many times you have a set of well known keys mixed with other dynamic keys, and you only care about the fixed ones and their type.
With destructuring is quite easy taking apart the known keys from the dynamic ones

const { fixedKey, knownKey, ...otherKeys} = someObject

So having all the "otherKeys" object have a mixed type just because fixedKey and knownKey didn't matched the type of the dynamic keys is an unnecessary trouble.

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