限制方法中的接口类型参数
Restrict interface type parameter in method
我想表达的是,只有当接口的类型参数符合特定约束条件时,方法才有意义。这是一个(非编译)示例:
interface Array<T> {
fold<B>(base: B, f: (acc: B, e: T) => B): B
sum(): T is number
}
Array.prototype.fold = function(base, f) {
let result = base
for (let i = 0; i < this.length; i++)
result = f(result, this[i])
return result
}
Array.prototype.sum = function() {
return this.fold(0, (acc, e) => acc + e)
};
[1, 'a', 3].sum() //? 1a3 <-- should be an error!
在这里,我试图表达 sum
只有在 T extends number
时才有意义。
你的想法是正确的,只是语法错误。
这就是你写的。
interface Array<T> {
sum(this: number[]): number;
}
注意我们如何使用 this
类型,它是一个合成参数,不会改变函数的元数。您尝试使用的语法虽然是一个有趣的猜测,但用于另一个目的,即类型保护。
有趣的是 this
上的类型注释优先于接口类型。您也可以声明一个通用参数,将其应用于 this
,并对 T
施加限制,以便它也可以组合。有很大的灵活性。
这里有一个有趣的,它结合了接口类型并用 this
对其进行了改进
interface Array<T> {
flatten(this: T[][]): T[];
}
我想表达的是,只有当接口的类型参数符合特定约束条件时,方法才有意义。这是一个(非编译)示例:
interface Array<T> {
fold<B>(base: B, f: (acc: B, e: T) => B): B
sum(): T is number
}
Array.prototype.fold = function(base, f) {
let result = base
for (let i = 0; i < this.length; i++)
result = f(result, this[i])
return result
}
Array.prototype.sum = function() {
return this.fold(0, (acc, e) => acc + e)
};
[1, 'a', 3].sum() //? 1a3 <-- should be an error!
在这里,我试图表达 sum
只有在 T extends number
时才有意义。
你的想法是正确的,只是语法错误。
这就是你写的。
interface Array<T> {
sum(this: number[]): number;
}
注意我们如何使用 this
类型,它是一个合成参数,不会改变函数的元数。您尝试使用的语法虽然是一个有趣的猜测,但用于另一个目的,即类型保护。
有趣的是 this
上的类型注释优先于接口类型。您也可以声明一个通用参数,将其应用于 this
,并对 T
施加限制,以便它也可以组合。有很大的灵活性。
这里有一个有趣的,它结合了接口类型并用 this
interface Array<T> {
flatten(this: T[][]): T[];
}