'How can I make TypeScript error on missing mapped key?
This is what I have:
type TransferType = 'INTERNAL' | 'WITHDRAWAL' | 'DEPOSIT'
type TransferEvents = Record<TransferType, Record<string, TypeFoo | TypeBar>>
export interface EventsTooltip extends TransferEvents {
some: string;
extra: number;
keys: boolean:
INTERNAL: Record<string, TypeFoo>;
WITHDRAWAL: Record<string, TypeBar>;
DEPOSIT: Record<string, TypeBar>;
}
Is it possible to make TypeScript throw an error if I add another type to TransferType, like 'CORRECTION', but forget to add it to EventsTooltip? While also retaining the ability to be more specific for the value type (TypeFoo or TypeBar) in the records?
Solution 1:[1]
You can use a generic type that simply returns the generic after doing a compile-time check on the generic:
type TransferType = 'INTERNAL' | 'WITHDRAWAL' | 'DEPOSIT'
type TypeFoo = { __lock1: never };
type TypeBar = { __lock2: never };
type TransferEvents = Record<TransferType, Record<string, TypeFoo | TypeBar>>
type CreateEventsTooltip<
// Compile-time check here.
T extends TransferEvents,
> = T;
export type EventsTooltip = CreateEventsTooltip<{
some: string;
extra: number;
keys: boolean;
INTERNAL: Record<string, TypeFoo>;
WITHDRAWAL: Record<string, TypeBar>;
DEPOSIT: Record<string, TypeBar>;
}>;
export type EventsTooltip2 = CreateEventsTooltip<{
some: string;
extra: number;
keys: boolean;
INTERNAL: Record<string, TypeFoo>;
WITHDRAWAL: Record<string, TypeBar>;
// We're missing "DEPOSIT" so it errors
// DEPOSIT: Record<string, TypeBar>;
}>;
Edit: Also, if you want those index signatures with shallower typing back from you extending back when it was using interfaces, then you can change the CreateEventsTooltip type to look like this:
type CreateEventsTooltip<T extends TransferEvents> = T & TransferEvents;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
