flowtype - 如何在 Flow 中使用通用字符串扩展 Error 接口?
问题描述
当我尝试Error
在 Flow 中扩展接口以使该name
属性成为强制性时,Flow 不会将我的泛型类型识别为字符串,尽管将它们明确描述为字符串。
当我写下:
interface CustomError<A: string, B: string> extends Error {
message: A;
name: B;
}
我收到这 2 个(相同的)错误:
- 无法扩展
Error
1,CustomError
因为A
[2] 与属性中的字符串 [3] 不兼容message
。 - 无法扩展
Error
1,CustomError
因为B
[2] 与属性中的字符串 [3] 不兼容name
。
奇怪的是它告诉我因为A
[2] 不兼容,什么时候A
应该被描述为string
...
解决方案
我也不清楚为什么它不起作用,但是这样的事情似乎没问题:
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
类。
推荐阅读
- excel - 我正在尝试在所有选定工作表的指定范围内粘贴某个公式
- android - 如何在向上滑动或单击事件时转换 CardView 的大小和形式?
- java - Java 安卓白屏
- auth0 - Paw 和 Auth0 观众
- javascript - 使用正则表达式的字符串中相似字符的唯一序列
- android - 认证后Android应用锁应用返回
- json - 带有 AND (&&) 的 Json 路径表达式
- python - Tkinter:将图标添加到菜单项中
- terraform - terraform apply 是否也会根据已部署的内容刷新状态?
- python - Dockerfile - debian Jessie 404:找不到包