Home > database >  Type 'unknown' is not assignable to type 'never' when using ReturnType<typeof
Type 'unknown' is not assignable to type 'never' when using ReturnType<typeof

Time:10-08

Hi all can someone help me with this please:

function guard <Data>({ handler }: { handler: (data: Data) => Promise<{ statusCode: number }> }) {
  return async (data: Data) => {
    const response = await handler(data);
    return response;
  };
}

const ping = guard<never>({
  handler: async () => {
    return { statusCode: 200 };
  }
});

export const events: Record<
  string,
  ReturnType<typeof guard>
> = {
  ping
};

on the part where I add ping to events, it will say:

Type '(data: never) => Promise<{ statusCode: number; }>' is not assignable to type '(data: unknown) => Promise<{ statusCode: number; }>'.
  Types of parameters 'data' and 'data' are incompatible.
    Type 'unknown' is not assignable to type 'never'.

While I could use any, I want to be specific with my typings and be able to use never whenever I won't actually use the parameter.

Here's an example code for the problem

Playground

CodePudding user response:

Let the inference do its job,

ping is not (data: never) => Promise<{ statusCode: number;}> but (data: unknown) => Promise<{ statusCode: number;}>

function guard<Data>({ handler }: { handler: (data: Data) => Promise<{ statusCode: number }> }) {
  return async (data: Data) => {
    const response = await handler(data);
    return response;
  };
}

const ping = guard({ // could also be guard<unknown>(...)
  handler: async (data) => {
    console.log(data);
    return { statusCode: 200 };
  }
});

export const events: Record<string, ReturnType<typeof guard>> = {
  ping // ok 
};

The other possibility being, setting the guard generic type to any : export const events: Record<string, ReturnType<typeof guard<any>>>

Playground

CodePudding user response:

The type system in typescript is built upon the formal definition of type theory, so if you want to understand why you're getting this error, you need to understand the basics of type theory.

I recommend reading this article: https://blog.logrocket.com/when-to-use-never-and-unknown-in-typescript-5e4d6c5799ad/

From the above mentioned article:

unknown is the set of all possible values. Any value can be assigned to a variable of type unknown. never is the empty set. There is no value that can be assigned to variable of type never. In fact, it is an error for the type of value to resolve to never because that would be a contradiction.

  • Related