繁体   English   中英

typescript:如何声明 function rturn type that inside object

[英]typescript: how to declare function rturn type that inside of object

我正在创建一个错误 object,其中包含多个返回 IErrorForm 类型的错误。 but if I focus on a function and set the return type of IErrorFunc, an error occurs in an object such as PermissionDenied and conversely, if I focus on the object and set the return type of IErrorObj, an error occurs in the function.

因此,如果我使用如下联合类型,则错误发生在 function 中。 错误信息是

'类型(来自:字符串)=> {成功:boolean; 代码:号码; 消息:字符串; }'没有属性成功,代码,消息类型'{成功:boolean; 代码:号码; 消息:字符串; }'。 ts(2739)

如何声明 object 的返回类型?

type IErrorForm = {
  sucess: boolean;
  code: number;
  message: string;
};
type IErrorsFunc = {
  (...args: any[]): {
    sucess: boolean;
    code: number;
    message: string;
  };
};

interface IErrorObj {
  [key: string]: { sucess: boolean; code: number; message: string };
}

export const CommonErrors: (IErrorObj | IErrorsFunc) = {
  unexpectedError(from: string) {
    return {
      sucess: false,
      code: 101,
      message: `Unexpected error from ${from}`,
    };
  },
  NotFound(object: string): IErrorForm {
    return {
      sucess: false,
      code: 102,
      message: `${object} not found`,
    };
  },
  permissionDenied: {
    sucess: false,
    code: 103,
    message: 'Permission denied: do not have permission.',
  },
  accessDenied(message: string): IErrorForm {
    return {
      sucess: false,
      code: 104,
      message: `Access denied: ${message}`,
    };
  },
};

看起来您的意图是让CommonErrors成为具有任意键的 object ,其值为IErrorFormIErrorsFunc 如果我们将该类型IErrorObj ,那么它看起来像:

interface IErrorObj {
  [key: string]: IErrorForm | IErrorsFunc;
}

使用string 索引签名为我们提供任意键,以及IErrorFormIErrorsFunc联合为我们提供非此即彼的行为。

如果我们这样做,那么您的代码编译不会出错:

export const CommonErrors: IErrorObj = {
  unexpectedError(from: string) {
    return {
      success: false,
      code: 101,
      message: `Unexpected error from ${from}`,
    };
  },
  NotFound(object: string): IErrorForm {
    return {
      success: false,
      code: 102,
      message: `${object} not found`,
    };
  },
  permissionDenied: {
    success: false,
    code: 103,
    message: 'Permission denied: do not have permission.',
  },
  accessDenied(message: string): IErrorForm {
    return {
      success: false,
      code: 104,
      message: `Access denied: ${message}`,
    };
  },
};

还值得注意的是, IErrorForm的返回类型与IErrorsFunc具有相同的形状,这意味着由于结构类型,我们可以重用该类型名称。 因此,您的最终类型集可能如下所示:

interface IErrorForm {
  success: boolean;
  code: number;
  message: string;
}

interface IErrorsFunc {
  (...args: any[]): IErrorForm
}

interface IErrorObj {
  [key: string]: IErrorForm | IErrorsFunc;
}

Playground 代码链接

暂无
暂无

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

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