Search code examples
typescriptenums

How to specify type for keys of type of enum in Typescript?


I have enum and type

export enum MyPerfectEnum {
    self = 'self',
    first = 'first',
    prev = 'prev',
    next = 'next',
    last = 'last'
}

export type MyPerfectType = {
    [key in MyPerfectEnum]?: string
}

and i have some method that returns the keys

export class SomeClassComponent extends React.Component<{
    links: MyPerfectType,
}> {

    public someMethod(): ???? {
        return Object.keys(this.props.links)
    }
}

I'm wondering how to specify return type for this method

I tried Array<keyof MyPerfectType>, but my IDE(phpStorm) thinks i am wrong and it is must be string[]


Solution

  • Object.keys's return type is string[], even if you pass in an object of a known type, such as an enum. This is because typescript types don't forbid excess properties, so the object may have more keys than the type definition accounts for.

    For example, the following is a perfectly legal value to pass into the links prop:

    const links = { 
      [MyPerfectEnum.self]: '/self',
      foo: '/bar'
    };
    return <SomeClassComponent links={links} />
    

    If you're sure that your object only has certain keys and want to override string[], you'll need to do that with a type assertion. For example:

    public someMethod(): (keyof MyPerfectEnum)[] {
     return Object.keys(this.props.links) as (keyof MyPerfectEnum)[]
    }