An index signature parameter type must be either 'string' or 'number' error

Viewed 1036

When I create this type on Typescript:

type TYPE_STORAGE<T extends { [k: string]: any }> = { [k: keyof T | 'all']: number };

or

type TYPE_STORAGE_2<T> = { [k: keyof T | 'all']: number };

the parser answers to me,

An index signature parameter type must be either 'string' or 'number'

I don't understand, what this said to me. Thanks for your answers!

1 Answers

What you're looking for is this:

// TYPE_STORAGE
type TYPE_STORAGE<T extends { [k: string]: any }> = { [k in keyof T | 'all']: number };

// TYPE_STORAGE_2
type TYPE_STORAGE_2<T> = { [k in keyof T | 'all']: number };

If all your properties are optional, then this:

// TYPE_STORAGE
type TYPE_STORAGE<T extends { [k: string]: any }> = { [k in keyof T | 'all']?: number };

// TYPE_STORAGE_2
type TYPE_STORAGE_2<T> = { [k in keyof T | 'all']?: number };

Notice the ? in the optional scenario.

Hope this helps you. Cheers !!!

Related