简体   繁体   English

object 文字和 function 的类型

[英]Types for object literal and function

I am making a function where it takes type and field as its arguments.我正在制作一个 function,它将类型和字段作为其 arguments。

Basically functions first argument is key of object errorTypes, and the second argument is errorArgTypes.基本上函数的第一个参数是 object errorTypes 的键,第二个参数是 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 TypeScript操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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