如何在Flow中使用通用字符串扩展Error接口?

时间:2018-11-19 01:53:32

标签: flowtype

当我尝试在Flow中扩展Error接口以使name属性为强制性时,尽管将通用类型明确描述为字符串,但Flow仍无法将我的通用类型识别为字符串。

当我这样写的时候:

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

我得到these 2 (same) errors

  • 无法使用Error扩展CustomError 1,因为A [2]与属性message中的字符串[3]不兼容。
  • 无法使用Error扩展CustomError 1,因为B [2]与属性name中的字符串[3]不兼容。

奇怪的是,它告诉我因为A [2]不兼容,当A立即描述为string时... < / p>

1 个答案:

答案 0 :(得分:1)

我也不清楚为什么它不起作用,但是类似seems to be ok

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允许throw any expression, not only Error children,因此您可能不需要扩展Error类。