Home > OS >  keyof on a nullable subtype, "not assignable to parameter of type 'never'"
keyof on a nullable subtype, "not assignable to parameter of type 'never'"

Time:05-28

I have a type, jsonReplyObject.

export type jsonReplyObject = {
  commands?: {
    'relogin'?: boolean
    'throttled'?: boolean
  },
  success?: boolean,
  message?: string,
};

And a function declaration like this

function foo(command: keyof jsonReplyObject['commands']) {}

When I try to call foo('relogin'), I get Argument of type 'string' is not assignable to parameter of type 'never'.

If I change the declaration of commands above from commands?: to commands:, it solves this error and keyof jsonReplyObject['commands'] works as I'd expect, enforcing that that argument is a possible key of commands. Unfortunately, it causes several other errors where instances of jsonReplyObject now require commands be provided.

What's the simplest way to fix this?

I've removed a lot of commands to keep this brief, but several commands are not of boolean type. They're of types relevant to their purpose.

CodePudding user response:

Use the NonNullable type :

function foo(command: keyof NonNullable<jsonReplyObject['commands']>) {}

Playground

CodePudding user response:

The built-in NonNullable utility type excludes null and undefined, so you can use keyof on that:

function foo(command: keyof NonNullable<jsonReplyObject['commands']>) {}

Previously, it gives you never because keyof undefined is never.

Another solution would be to use the built-in Required type:

function foo(command: keyof Required<jsonReplyObject>['commands']) {}
  • Related