如何定义装饰器的类型以防止丢失装饰函数的类型信息?
How to define type of decorator to prevent losing type info of decorated function?
鉴于以下情况:
// @flow
function a(s: string): ?string {
return s === '' ? null : s
}
function decorate(f: Function): Function {
return f
}
const b = decorate(a)
a(12)
b(12)
当你用一个数字调用 a 时,flow 会抛出一个错误,但当你用一个数字调用 b 时,不会抛出错误
13: a(12)
^^ number. This type is incompatible with the expected param type of
3: function a(s: string): ?string {
^^^^^^ string
有没有这样的方法可以做类似的事情
function decorate(f: Function): typeof(f) {
return f
}
使得装饰函数可以正确进行类型检查,而不会明确限制装饰 returns 喜欢的内容
function decorate(f: Function): (string) => ?string {}
或复制 b 上的类型信息,如
const b: typeof(a) = decorate(a)
您需要为此创建函数 polymorphic:
function decorate<T: Function>(f: T): T {
return f
}
您可以参数化您的函数:
function decorate(f: Function): Function {
return f;
}
可以
function decorate<T>(f: T): T {
return f;
}
说“结果的类型与输入的类型相同。
鉴于以下情况:
// @flow
function a(s: string): ?string {
return s === '' ? null : s
}
function decorate(f: Function): Function {
return f
}
const b = decorate(a)
a(12)
b(12)
当你用一个数字调用 a 时,flow 会抛出一个错误,但当你用一个数字调用 b 时,不会抛出错误
13: a(12)
^^ number. This type is incompatible with the expected param type of
3: function a(s: string): ?string {
^^^^^^ string
有没有这样的方法可以做类似的事情
function decorate(f: Function): typeof(f) {
return f
}
使得装饰函数可以正确进行类型检查,而不会明确限制装饰 returns 喜欢的内容
function decorate(f: Function): (string) => ?string {}
或复制 b 上的类型信息,如
const b: typeof(a) = decorate(a)
您需要为此创建函数 polymorphic:
function decorate<T: Function>(f: T): T {
return f
}
您可以参数化您的函数:
function decorate(f: Function): Function {
return f;
}
可以
function decorate<T>(f: T): T {
return f;
}
说“结果的类型与输入的类型相同。