Create a type where its attributes are in a interface/type using generics

Viewed 26

I am create a type based on API response for AxiosError.

errors: {
   Property: [string]
}

Example:

export interface User {
  username: string;
  password: string;
}

Expected API output

errors: {
   username: [string]
   password: [string]
}

I'm currently writing the type (below) however I received the following error and will need advice whether I'm implementing correctly and the solution to this.

export type ClassError<T> = {
 [keys in T]: Array<string>; //Type 'T' is not assignable to type 'string | number | symbol'
}

export type PayloadError<T> = {
 errors: string | ClassError<T>;
}
1 Answers

You're just looking for the keyof type operator which gives you the union of known keys of a type:

export type ClassError<T> = {
    [K in keyof T]: Array<string>;
}

type UserErrors = ClassError<User>;
/* type UserErrors = {
    username: string[];
    password: string[];
} */

Playground link to code

Related