-
Notifications
You must be signed in to change notification settings - Fork 12.9k
Closed as not planned
Closed as not planned
Copy link
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
π Search Terms
record index indexed type template literal type assignable assignability
β Viability Checklist
- 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 isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β 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.
π» Use Cases
- What do you want to use this for? - Safer use of
Record
types when keyed by template literal types. - What shortcomings exist with current approaches? - We could use a
Map
instead, butMap
s don't survive the roundtrip from JSON and back, and so can be harder to use when crossing the network boundary. - What workarounds are you using in the meantime? - For now we're converting to
Map
s where we can, and are viewing existingRecord
s with suspicion.
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created