首页 > 解决方案 > 如何在 Flow 中使用通用字符串扩展 Error 接口?

问题描述

当我尝试Error在 Flow 中扩展接口以使该name属性成为强制性时,Flow 不会将我的泛型类型识别为字符串,尽管将它们明确描述为字符串。

当我写下:

interface CustomError<A: string, B: string> extends Error {
  message: A;
  name: B;
}

我收到这 2 个(相同的)错误

奇怪的是它告诉我因为A[2] 不兼容,什么时候A应该被描述为string...

标签: flowtype

解决方案


我也不清楚为什么它不起作用,但是这样的事情似乎没问题:

class CustomError<A: string, B: string> extends Error {

  constructor(name: A, message: B) {
    super(name);
     this.name = name;
    this.message = message;
  }
}

type A = 'A' | 'A1';
type B = 'B' | 'B1';

class SpecificError extends CustomError<A, B> {}

//throw new SpecificError('a', 'c'); //error, wrong argument

throw new SpecificError('A', 'B'); //ok

另外,请注意 js 允许抛出任何表达式,而不仅仅是 Error children,因此您可能不需要扩展Error类。


推荐阅读