import type {OmitIndexSignature} from 'type-fest';
interface Example {
// These index signatures will be removed.
[x: string]: any
[x: number]: any
[x: symbol]: any
[x: `head-${string}`]: string
[x: `${string}-tail`]: string
[x: `head-${string}-tail`]: string
[x: `${bigint}`]: string
[x: `embedded-${number}`]: string
// These explicitly defined keys will remain.
foo: 'bar';
qux?: 'baz';
}
type ExampleWithoutIndexSignatures = OmitIndexSignature<Example>;
// => { foo: 'bar'; qux?: 'baz' | undefined; }
Omit any index signatures from the given object type, leaving only explicitly defined properties.
This is the counterpart of
PickIndexSignature.Use-cases:
This type was taken from this StackOverflow answer.
It relies on the fact that an empty object (
{}) is assignable to an object with just an index signature, likeRecord<string, unknown>, but not to an object with explicitly defined keys, likeRecord<'foo' | 'bar', unknown>.(The actual value type,
unknown, is irrelevant and could be any type. Only the key type matters.)Instead of causing a type error like the above, you can also use a conditional type to test whether a type is assignable to another:
Using a mapped type, you can then check for each
KeyTypeofObjectType......whether an empty object (
{}) would be assignable to an object with thatKeyType(Record<KeyType, unknown>)...If
{}is assignable, it means thatKeyTypeis an index signature and we want to remove it. If it is not assignable,KeyTypeis a "real" key and we want to keep it.