简体   繁体   中英

Types for object literal and function

I am making a function where it takes type and field as its arguments.

Basically functions first argument is key of object errorTypes, and the second argument is errorArgTypes.

I am getting an error // All type parameters are unused; for below code.

please advise.

type errorArgTypes = {
  field: string;
};

const errorTypes = {
  INTERNAL_SERVER_ERROR: {
    code: 500,
    message: "Internal Server Error 😵",
  },
  AUTH_NOT_FOUND: {
    code: 401,
    message: "User Not Found ❗️",
  },
  AUTH_ALREADY_EXIST: {
    code: 404,
    message: "User Already Existed 👀",
  },
  AUTH_NOT_MATCH: {
    code: 402,
    message: "Email or Password Not Match 🥑",
  },
  AUTH_NO_PERMISSION: {
    code: 403,
    message: "No Permission 🔫",
  },
  DATA_NOT_FOUND: {
    code: 401,
    message: "No Data 😕",
  },
};

type typeOfError = key in  errorTypes;

const foo = {
  "hello": "hola"
};

let data: { [key in keyof typeof foo]:number} & { name: string, index: number }[] = [] as any;



function prop<T, K extends keyof T>(obj: T, key: K) {
  return obj[key];
}

// All type parameters are unused;

const BaseError = <Key extends keyof typeOfError, errorArgTypes>(type, arg?) => {
  const { code, message } = errorTypes[type];
  return new ApolloError(message, code, arg);
};

Try this approach:

const errorTypes = {
  INTERNAL_SERVER_ERROR: {
    code: 500,
    message: "Internal Server Error 😵",
  },
  AUTH_NOT_FOUND: {
    code: 401,
    message: "User Not Found ❗️",
  },
  AUTH_ALREADY_EXIST: {
    code: 404,
    message: "User Already Existed 👀",
  },
  AUTH_NOT_MATCH: {
    code: 402,
    message: "Email or Password Not Match 🥑",
  },
  AUTH_NO_PERMISSION: {
    code: 403,
    message: "No Permission 🔫",
  },
  DATA_NOT_FOUND: {
    code: 401,
    message: "No Data 😕",
  },
};

type errorArgTypes = {
  field: string;
};

const BaseError = <
  Key extends keyof typeof errorTypes,
  errorArgTypes
>(type: Key, arg?: errorArgTypes) => {
  const { code, message } = errorTypes[type];

  return new ApolloError(message, code, arg);
};

TypeScript playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM