DEV Community 👩‍💻👨‍💻

Cover image for Quick tip 1 - How to remove an index signature from a type?
Denis Sirashev
Denis Sirashev

Posted on

Quick tip 1 - How to remove an index signature from a type?

Prehistory

During my work as a React developer, I found a situation when you need to remove an index signature from a type.
A simple example, the type utility Omit doesn't work properly when a type has an index signature. I've worked with the react-select js library and I'd wanted to get all base attributes of a SelectProps using Omit<SelectProps>, but received an any type. Trying to solve the problem, I located a problem inside SelectProps - it extends from a SelectComponentsProps which is a mapped type.

Solution

The solution is to remove the index signature. How to do it? In TypeScript 4.1 and onwards, you can re-map keys in mapped types with an as clause. We can create a utility type with generic and it will remove all index signatures in a specified type:

type RemoveIndexSignature<T> = {
  [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: T[K]
}
Enter fullscreen mode Exit fullscreen mode

What does it do?

It iterates through the keys of a type and checks, if a type of the key is string, number, or symbol, then removes it, otherwise keeps it in the type. In the end, you'll get a clean type without any index signature in it.

Example

type Base = { [key: string]: boolean }

type User = Base & {
  email: string
  name?: string
}

type Cleaned = RemoveIndexSignature<User>

type Cleaned = {
  email: string
  name?: string
}
Enter fullscreen mode Exit fullscreen mode

Photo by Alex Kotliarskyi on Unsplash

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.