首页 文章

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

提问于
浏览
1

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

我写的时候:

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

我得到these 2 (same) errors

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

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

奇怪的是,它告诉我因为 A [2]当 A 应该被立即描述为_398743时是不相容的...

1 回答

  • 1

    它's also not clear for me why it doesn'工作,但是这样的事情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 类 .

相关问题