typescript中函数的操作
此函数将包装另一个作为参数传入的函数 问题是当typescript中函数的操作,typescript,functional-programming,Typescript,Functional Programming,此函数将包装另一个作为参数传入的函数 问题是当stricnullchecks模式设置为true时,IDE中将出现错误 我能想到的唯一解决此错误的方法是添加以下行: export const wrapCountable = (func: Function): Function => { let result: Function & { __times?: number } = () => { //result.__times = result.__ti
stricnullchecks
模式设置为true
时,IDE中将出现错误
我能想到的唯一解决此错误的方法是添加以下行:
export const wrapCountable = (func: Function): Function => {
let result: Function & { __times?: number } = () => {
//result.__times = result.__times || 0
result.__times++
let value = null
try {
value = func()
} catch (e) {
throw e
}
return value
}
result.__times = 0
return result
}
然而,我认为这不是一个完美的解决方案。那么正确的方法是什么?编译器没有意识到
结果。
中的箭头函数调用时,肯定会定义\uu次。如果您不想更改发出的JavaScript,可以使用
告诉编译器您比它更聪明,并且结果。将定义\u次
:
result.__times = result.__times || 0
这将抑制错误。但是它不是类型安全的。。。您可以注释掉结果。_times=0
行,错误仍将被抑制。类型断言,包括代码>使对编译器撒谎成为可能。尽管如此,我还是希望在这种情况下,您可以做出明智的决定,使用断言
也就是说我可能会把你的函数压缩成
export const wrapCountable = (func: Function): Function => {
let result: Function & { __times?: number } = () => {
result.__times!++ // notice the ! here
let value = null
try {
value = func()
} catch (e) {
throw e
}
return value
}
result.__times = 0
return result
}
const wrapCountable=(func:()=>T)=>{
const result=Object.assign(()=>{
结果。_次++;
返回func();
},{uuuu次:0});
返回结果;
}
常数18=可计数(()=>18);
//常量十八:(()=>数字)和{uuu次:数字}
console.log(十八个());//18
console.log(十八个());//18
console.log(十八次);//2.
使用泛型T
不丢失返回值的类型,使用Object.assign()
不必允许\u次未定义,如果没有则尝试/catch
块,该块似乎没有任何作用(重新抛出相同的异常是不可行的,对吗?)
无论如何,希望这能有所帮助。祝你好运!编译器没有意识到的结果。调用结果中的箭头函数时,肯定会定义\uu次
。如果你不想更改发出的JavaScript,你可以使用!
告诉编译器你比它更聪明,而且不会hat结果。将定义\uuu时间
:
result.__times = result.__times || 0
这将抑制错误。但它不是类型安全的…您可以注释掉结果。_times=0
行,错误仍将被抑制。包括!
在内的类型断言可能会对编译器撒谎。不过,我希望在这种情况下,您可以做出明智的决定,使用断言
也就是说我可能会把你的函数压缩成
export const wrapCountable = (func: Function): Function => {
let result: Function & { __times?: number } = () => {
result.__times!++ // notice the ! here
let value = null
try {
value = func()
} catch (e) {
throw e
}
return value
}
result.__times = 0
return result
}
const wrapCountable=(func:()=>T)=>{
const result=Object.assign(()=>{
结果。_次++;
返回func();
},{uuuu次:0});
返回结果;
}
常数18=可计数(()=>18);
//常量十八:(()=>数字)和{uuu次:数字}
console.log(seark());//18
console.log(seark());//18
console.log(十八次);//2
使用泛型T
不丢失返回值的类型,使用Object.assign()
不必允许\u次未定义,如果没有则尝试/catch
块,该块似乎没有任何作用(重新抛出相同的异常是不可行的,对吗?)
不管怎样,希望这有帮助。祝你好运