当我尝试在Flow中扩展Error
接口以使name
属性为强制性时,尽管将通用类型明确描述为字符串,但Flow仍无法将我的通用类型识别为字符串。
当我这样写的时候:
interface CustomError<A: string, B: string> extends Error {
message: A;
name: B;
}
Error
扩展CustomError
1,因为A
[2]与属性message
中的字符串[3]不兼容。 Error
扩展CustomError
1,因为B
[2]与属性name
中的字符串[3]不兼容。 奇怪的是,它告诉我因为A
[2]不兼容,当A
立即描述为string
时... < / p>
答案 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
类。